How can I compare two lists with xunit test

2020-03-26 01:25发布

问题:

I am currently trying to compare two lists, with the same items in it, with xUnit but getting an error while running.

Assert.Equal(expectedList, actualList);

Error:

"Assert.Equal() Failure"
Expected: List<myObject> [myObject { modifier = '+', name = "name", type = "string" }, myObject { modifier = '+', name = "age", type = "int" }]
Actual:   List<myObject> [myObject { modifier = '+', name = "name", type = "string" }, myObject { modifier = '+', name = "age", type = "int" }]

回答1:

This has to do with object equality.

MyObject does not implement the Equals method. By default you get a reference equality. I assume you have two different objects for MyObject.

Meaning it does not matter that your List holds the similar object(meaning with same values) they are not of the same reference, so your test checks that, this is why it fails.

internal class MyObject
{
    {
        public char Modifier { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }

    }
}


            [Fact]
            public void ListMyObject()
            {
                var list1 = new List<MyObject>
                {
                    new MyObject{ }
                };
                var list2 = new List<MyObject>
                {
                    new MyObject{ }
                };

                Assert.Equal(list1, list2); // Fails
            }

When we update our class to this.

internal class MyObject
    {
        public char Modifier { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        //When i add this to my class.
        public override bool Equals(object obj)
        {
            return this.Name == ((MyObject)obj).Name;
        }
    }

Also as mentioned in the comments by Jonathon Chase.

It is a good idea to override the GetHashCode() method as well. It is preferred to inherit from IEquatable<T> so you can avoid casting.

Everything goes green.

        [Fact]
        public void ListMyObject()
        {
            var list1 = new List<MyObject>
            {
                new MyObject{ Name = "H" }
            };
            var list2 = new List<MyObject>
            {
                new MyObject{ Name = "H" }
            };

            Assert.Equal(list1, list2); //Passes
        }