5

Writing UnitTests with MSTest I want to assert the equality of a return value vs. the one I'm expecting.

Expected type is a custom type that does not implement the IComparable interface nor the IEquatable interface, thats why I want to give Assert.AreEqual a possibility to compare the two objects.

I am aware that this possibility exists in CollectionAssert.AreEqual. This method however requires two ojects that inherit ICollection which my objects do not.

Why does Assert.AreEqual not allow me to specify a custom comparer? Am I missing something?

buddybubble
  • 1,269
  • 14
  • 33
  • Hard to say why it's not supported! ;-) I would also use the workaround suggested by Stephen Byrne. – Jocke Oct 23 '13 at 10:43

1 Answers1

2

Not sure if this is the actual reason, but what if your custom IComparer was faulty - your unit test would be meaningless (bearing in mind that the test framework has no way to tell if you wrote unit tests for it let alone if they are "correct")

Could you just create a comparer in your test?

var com = new MyComparer<Foo>();
int expected=0;
int actual = com.Compare(a,b);
if (actual!=0)
{
  Assert.Fail("oops");
}

Maybe not ideal, but should work... I also found this question from a few years ago on msdn, with no answers - but an interesting approach to the workaround by the question poster.

Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51
  • I don't think thats the reason. I thought about writing a comparer in the unit test itself and then providing that as an argument to the assert. It would be part of the unit tests themselfes and of course I have to rely on my tests being written correctly. Regarding your example: Yeah thats what I did in the end, but thats just a workaround. It is, for example, difficult to tell why the two compared object are not identical – buddybubble Oct 23 '13 at 12:21
  • @buddybubble - yes I doubt it's the actual reason, it could just have been a simple as the framework designers just not thinking about it :) I found another workaround which I have updated into my answer for posterity. – Stephen Byrne Oct 23 '13 at 12:28