I have a class, Foo
, from a third party library that I check for equality against another instance using NUnit,
Assert.AreEqual(foo1, foo2);
When the objects are different I get the expected failure,
Expected: Foo
But was: Foo
But the error message isn't very helpful. I know NUnit uses ToString
to show the error message but I can't override that here.
Does NUnit provide an API to override this behaviour so I can supply my own ToString
implementation? I can't see anything on the Assert.AreEqual
and Assert.That
APIs
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.
ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.
One more additional way not mentioned in the answer is to use following Visual Studio extension: https://marketplace.visualstudio.com/items?itemName=DavideLettieri.AutoToString. Once extension is installed, hit Ctrl + . inside class body, and there will be additional Generate ToString() action available.
You can add specific formatting code for any Type and NUnit will use it. See https://github.com/nunit/docs/wiki/TestContext#addformatter
This feature was added in NUnit 3.2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With