[英]Nunit: Check that two objects are the same
I have an object 我有一个对象
public class Foo
{
public string A{ get; set; }
public string B{ get; set; }
}
I am comparing the return value from the SUT when it returns null for A and B like this. 我正在比较SUT的返回值,当它为A和B返回null时,就像这样。
Assert.That(returnValue, Is.EqualTo(new Foo { A = null, B = null}));
This did not work, so I tried 这没用,所以我试过了
Assert.That(returnValue, Is.SameAs(new Foo { A = null, B = null}));
This didn't work either. 这也不起作用。
I get a message like 我得到一条消息
Expected: same as <Namespace+Foo>
But was: <Namespace+Foo>
What am I doing wrong? 我究竟做错了什么?
From nunit documentation , 从nunit文档 ,
When checking the equality of user-defined classes, NUnit makes use of the Equals override on the expected object.
在检查用户定义的类的相等性时,NUnit在预期的对象上使用Equals覆盖。 If you neglect to override Equals, you can expect failures non-identical objects.
如果忽略覆盖Equals,则可能会出现非相同对象的故障。 In particular, overriding operator== without overriding Equals has no effect.
特别是,重写operator ==而不覆盖Equals没有任何效果。
You can however supply your own comparer to test if the values are equal for the properties. 但是,您可以提供自己的比较器来测试属性的值是否相等。
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.
如果测试相等性的默认NUnit或.NET行为无法满足您的需求,则可以通过“使用”修饰符提供自己的比较器。 When used with EqualConstraint, you may supply an IEqualityComparer, IEqualityComparer, IComparer, IComparer;
当与EqualConstraint一起使用时,您可以提供IEqualityComparer,IEqualityComparer,IComparer,IComparer; or Comparison as the argument to Using.
或比较作为使用的参数。
Assert.That( myObj1, Is.EqualTo( myObj2 ).Using( myComparer ) );
So in this case your comparer would be 所以在这种情况下你的比较器会是
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();
}
}
Nunit is comparing the two objects objects by reference so it is showing the two objects are not equal. Nunit正在通过引用比较两个对象对象,因此它显示两个对象不相等。 You will have to override the
Equals
method in your object class. 您必须覆盖对象类中的
Equals
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.