C# UnitTest - 如果参数为 null,Assert.AreEqual() 不会调用 Equals
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/460371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# UnitTest - Assert.AreEqual() does not call Equals if the argument is null
提问by mafu
i recently stumbled upon a seemingly weird behavior that Google completely failed to explain.
我最近偶然发现了一种 Google 完全无法解释的看似奇怪的行为。
using Microsoft.VisualStudio.TestTools.UnitTesting;
class TestClass
{
public override bool Equals(object obj)
{
return true;
}
}
[TestMethod]
public void TestMethod1()
{
TestClass t = new TestClass ();
Assert.AreEqual (t, null); // fails
Assert.IsTrue (t.Equals (null)); // passes
}
I would expect this test to succeed. However, in Visual Studio 2008 / .NET 3.5 it fails. Is it intended to be like that or is it a bug?
我希望这个测试成功。但是,在 Visual Studio 2008 / .NET 3.5 中它失败了。它是打算那样还是它是一个错误?
采纳答案by Jon Skeet
Your TestClass violates the contract of Object.Equals
. Assert.AreEqual
is relying on that contract, quite reasonably.
您的 TestClass 违反了 的合同Object.Equals
。Assert.AreEqual
非常合理地依赖该合同。
The docs state (in the list of requirements):
文档状态(在要求列表中):
- x.Equals(a null reference (Nothing in Visual Basic)) returns false.
- x.Equals(空引用(在 Visual Basic 中为 Nothing))返回 false。
回答by Jon Limjap
When testing for nulls, do not use Assert.AreEqual
.
测试空值时,不要使用Assert.AreEqual
.
You have to use Assert.IsNull()
for that.
你必须使用Assert.IsNull()
它。
回答by Xn0vv3r
The first test fails. Test if "t" is null, which isn't, because you initialized the t with a new TestClass object.
第一次测试失败。测试“t”是否为空,这不是,因为您使用新的 TestClass 对象初始化了 t。
The second test, passes, because t.Equals always returns true.
第二个测试通过了,因为 t.Equals 总是返回 true。
If one test fails, the whole TestMethod1 is marked as failed.
如果一个测试失败,则整个 TestMethod1 被标记为失败。
回答by gkrogers
No, it's correct - you've initialised t to a new TestClass object, which isn't null, so the assertion fails.
不,这是正确的 - 您已将 t 初始化为一个新的 TestClass 对象,该对象不为空,因此断言失败。
回答by mafu
If i get you right, it is actually intended that AreEqual(anythingButNull, null)
always return false?
如果我猜对了,实际上是打算AreEqual(anythingButNull, null)
始终返回 false?
(edit) The reason i wondered is because the test for null, as required by the contract of Equals, is not called when unittesting the class. So because AreEqual relies on the contract, it fails to check if my class also complies with the contract. So i guess i have to use the workaround of Assert.IsFalse(blah.Equals(null))
.
(编辑)我想知道的原因是因为在对类进行单元测试时,没有调用 Equals 合同要求的 null 测试。所以因为 AreEqual 依赖于契约,它无法检查我的类是否也遵守契约。所以我想我必须使用Assert.IsFalse(blah.Equals(null))
.