How can I compare two lists with xunit test

后端 未结 1 1503
遇见更好的自我
遇见更好的自我 2021-01-13 17:16

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);         


        
相关标签:
1条回答
  • 2021-01-13 17:38

    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
            }
    
    0 讨论(0)
提交回复
热议问题