Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# UnitTest - Assert.AreEqual() does not call Equals if the argument is null

i recently stumbled upon a seemingly weird behavior that Google completely failed to explain.


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?

like image 376
mafu Avatar asked Jan 20 '09 07:01

mafu


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C and C++ meaning?

C is a function driven language because C is a procedural programming language. C++ is an object driven language because it is an object oriented programming. Function and operator overloading is not supported in C. Function and operator overloading is supported by C++. C is a function-driven language.


2 Answers

Your TestClass violates the contract of Object.Equals. Assert.AreEqual is relying on that contract, quite reasonably.

The docs state (in the list of requirements):

  • x.Equals(a null reference (Nothing in Visual Basic)) returns false.
like image 167
Jon Skeet Avatar answered Sep 30 '22 01:09

Jon Skeet


When testing for nulls, do not use Assert.AreEqual.

You have to use Assert.IsNull() for that.

like image 34
Jon Limjap Avatar answered Sep 30 '22 02:09

Jon Limjap