Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm writing a unit test for some .net code I've written.

I'm familiar with writing code like this:

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

In the case that the arguments are integers, it's clear what to expect the code to do.

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

If I've written a custom classed called MyClass, how can I control when Assert.AreEqual passes and failed with objects of type MyClass?

like image 232
Vivian River Avatar asked Mar 23 '23 11:03

Vivian River


1 Answers

The official documentation is pretty laconical and doesn't explain it, so I believe that if the objects are not primitives, then their references will be compared.

That is, two references to the same object would evaluate as being equal; two clones of a same object would evaluate as being different. Unless you overload the Equals() instance method of the class(es) those objects belong to, or the == operator for said class(es).

Also see Reed Copsey's answer.

like image 105
Geeky Guy Avatar answered Apr 25 '23 11:04

Geeky Guy