Nunit:检查两个对象是否相同

Nunit: Check that two objects are the same

我有对象

 public class Foo
            {
                public string A{ get; set; }
                public string B{ get; set; }
            }

我正在比较来自 SUT 的 return 值,当它对 A 和 B 来说 return 为 null 时。

Assert.That(returnValue, Is.EqualTo(new Foo { A = null, B = null}));

这没用,所以我试了

Assert.That(returnValue, Is.SameAs(new Foo { A = null, B = null}));

这个也没用。

我收到这样的消息

 Expected: same as <Namespace+Foo>
 But was:  <Namespace+Foo>

我做错了什么?

Nunit 通过引用比较两个对象,因此显示两个对象不相等。您必须覆盖对象 class.

中的 Equals 方法

来自 nunit documentation,

When checking the equality of user-defined classes, NUnit makes use of the Equals override on the expected object. If you neglect to override Equals, you can expect failures non-identical objects. In particular, overriding operator== without overriding Equals has no effect.

但是您可以提供自己的比较器来测试属性的值是否相等。

If the default NUnit or .NET behavior for testing equality doesn't meet your needs, you can supply a comparer of your own through the Using modifier. When used with EqualConstraint, you may supply an IEqualityComparer, IEqualityComparer, IComparer, IComparer; or Comparison as the argument to Using.

Assert.That( myObj1, Is.EqualTo( myObj2 ).Using( myComparer ) );

所以在这种情况下,您的比较器将是

    public class FooComparer : IEqualityComparer
    {
        public bool Equals(Foo x, Foo y)
        {
            if (x.A == y.A && x.B == y.B)
            {
                return true;
            }
            return false;
        }
        public int GetHashCode(Foo inst)
        {
            return inst.GetHashCode();
        }
    }