Compare Anything for Equality

Comparing objects for equality can be a pain in automated tests in C#. It works fine for primitive data types and even collections based on IEnumerable<T>, when you use NUnit’s Assert-functions:

But once you  enter the realm of custom data types, you’re lost:

To make such a comparison work, you need to implement your own Equals() function and more.

That’s fine, when you need that in your code anyway. But it’s overkill to do it just for testing purposes.

However, in my experience, object comparisons in production code are far less frequent than in test code. That way, overriding Equals() etc. just makes testing harder – as much so that developers don’t write automated tests at all.

That’s bad, I’d say.

And switching to a language like F# which solves this problem by default is not an option for most.

The Equalidator to the rescue

But don’t despair. Help is available from the Equalidator. It’s a little library I wrote a couple of years back.

You can add the Equalidator package from NuGet. Or you can compile the tool yourself; it’s hosted on GitHub.

With the Equalidator it’s easy to check any two object graphs for equality. As a simple example comparison from above which did not work with NUnit:

But you can go deeper. Let’s compare two trees:

If the two object graphs are equal, i.e. contain the same values, then nothing happens. But if Equalidator finds a difference, it throws an exception.

Currently this exception is a bit broad brush, but still… the comparison is done dilligently and you know if the two graphs “look the same”.

Equalidator comes with one switch only, currently at least. You can choose whether collections should be compared with strict type checking – and int[] then is never equal to a List<int> – or whether loose type checking should be used like this:

The default is false for the last parameter meaning strict type checking.

I hope this little tools makes it easier for you to write automated tests. So I hope you’ll write more of them from now on 😉

If you’ve any suggestions for Equalidator feel free to clone the repo, improve the code, and send me a pull request. (There is even some design documentation in the repo to make it a bit easier for you to find your way around in the code.)

Posted in English postings.