简体   繁体   English

使用NUnit 2.6,是否可以具有两个对象,例如Assert.AreEqual和Assert.AreNotSame都为TRUE?

[英]With NUnit 2.6, is it possible to have two objects such that Assert.AreEqual and Assert.AreNotSame are BOTH TRUE?

To all: 对所有人:

I am trying to write a short C# application in which I'm trying to run two NUnit Assert statements for which I want BOTH to be true: 我正在尝试编写一个简短的C#应用​​程序,在其中尝试运行两个我希望两者都为真的NUnit声明语句:

Assert.AreEqual(object1, object1);
Assert.AreNotSame(object1, object2);

It seems possible but I have not had luck making this particular circumstance happen. 似乎有可能,但我没有让这种特殊情况发生的运气。 I want to instantiate two objects (object1, object2 above) that should evaluate true when using .Equals() but should evaluate false if using the " == " operator. 我想实例化两个对象(上面的object1,object2),使用.Equals()时应评估为true,但如果使用“ == ”运算符,则应评估为false。

Can NUnit do this? NUnit可以这样做吗?

Thanks! 谢谢!

A conditional yes to the first question and title. 第一个问题和标题的条件为是。 No to the last the one about == operator! 否最后一个==运算符!

This works 这有效

var object1 = new MyObject(someparameter);
var object2 = new MyObject(someotherparameter);

Assert.AreNotSame(object1, object2);
Assert.AreEqual(object1, object2); // See following

But only if you have overridden the Equals() method of the object in a way that it evaluates as true. 但仅当您以某种对象的Equals()方法评估为true的方式重写了该方法时。 It's up to you to define equality for your own objects. 由您决定自己对象的相等性。

On the other hand, this fails 另一方面,这失败了

var object1 = new object();
var object2 = new object();

Assert.AreNotSame(object1, object2);
Assert.AreEqual(object1, object2); // Fails!

The failure is because object equality is defined in .NET as being the same object. 失败是因为在.NET中将object相等定义为同一对象。 The two only behave differently for classes where equality has been defined in a different way. 对于以不同方式定义相等性的类,两者的行为仅不同。 That's true whether the Type is a .NET Type or one of your own. 无论Type是.NET Type还是您自己的类型都是如此。

The == operator on object gives object equality (same object). object上的==运算符使对象相等(相同的对象)。 It too only works differently for Types on which it has been defined differently. 它也仅对定义不同的类型起作用。 For your own Types, you would have to define it yourself if you want it to work. 对于您自己的类型,如果希望它可以工作,则必须自己定义。

By the way, your question really has nothing to do with NUnit per se. 顺便说一句,您的问题实际上与NUnit无关。 NUnit mostly tries to mimic what the .NET framework does for equality, although it adds a few "extras" like allowing ints to be equal to doubles when using an assert. NUnit大多尝试模仿.NET框架为实现相等所做的事情,尽管它添加了一些“附加”,例如在使用断言时允许将int等于double。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM