How does Assert.AreEqual compare two objects in .net unit tests?

I am writing unit test for some .net code that I wrote.

I am familiar with writing code as follows:

int expected = 10; int actual = multiplyByTwo(5); Assert.AreEqual(expected, actual); 

In the case where the arguments are integers, it is clear what to expect from the code.

What does the code do when the arguments passed are objects?

If I wrote a custom class called MyClass , how can I control when Assert.AreEqual passes and fails with objects like MyClass ?

+4
source share
3 answers

The official documentation is rather concise and does not explain this, so I believe that if objects are not primitive, then their links will be compared.

That is, two references to the same object will be evaluated as equal; two clones of the same object will be evaluated as different. If you do not overload the Equals() instance method of the class (s) to which these objects belong, or the == operator for the specified class (s).

Also see Reed Copsi's answer.

+4
source

What does the code do when the arguments passed are objects?

In this case, this is not so. It calls Assert.AreEqual<int>(expected, actual); .

The Assert.AreEqual method has many overloads . In this case, the best match for the two Int32 values ​​is overall overload . Since this is the β€œbest fit,” the compiler will choose this overload.

It, internally, will work with integers:

Checks that the two specified data types of the type are equal using the equality operator.

Regarding the second part of your question:

If I wrote a custom class called MyClass, how can I control when Assert.AreEqual passes and fails with objects like MyClass?

Assert.AreEqual uses the equality operator (==) to validate as defined above.

+3
source

If the objects are serializable, you can serialize them and then compare the serialized versions.

You can use this XmlSerialize extension method to handle serialization.

For example, when comparing Cat instances, the following psuedo code demonstrates this

 var expected = GetExpectedInstance(); // returns the expected result var actual = CallMethodUnderTest(); // get the actual result var e = expected.XmlSerialize<Cat>(); var a = actual.XmlSerialize<Cat>(); Assert.AreEqual(e, a); 
0
source

Source: https://habr.com/ru/post/1487361/


All Articles