Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

In this case, it's not. It's calling Assert.AreEqual<int>(expected, actual);.

The Assert.AreEqual method has many overloads. In this case, the best match for two Int32 values is the generic overload. Since this is the "best match", the compiler will choose this overload.

It, internally, will work with integers by:

Verifies that two specified generic type data are equal by using the equality operator.

As for the second part of your question:

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

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

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

You can use this XmlSerialize extension method to handle the serialization.

For example when comparing instances of a class Cat, 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top