如何使用XUnit测试比较两个列表 [英] How can I compare two lists with xunit test

查看:68
本文介绍了如何使用XUnit测试比较两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将两个具有相同项目的列表与xUnit进行比较,但是在运行时出现错误.

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

错误:

"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" }]

推荐答案

这与对象相等有关.

MyObject未实现Equals method.默认情况下,您获得引用相等性.我假设您有MyObject的两个不同对象.

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

也如乔纳森·蔡斯(Jonathon Chase)的评论中所述.

Also as mentioned in the comments by Jonathon Chase.

override GetHashCode()方法也是一个好主意.最好从IEquatable<T>继承,这样可以避免强制转换.

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.

一切都变成绿色.

        [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
        }

这篇关于如何使用XUnit测试比较两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆