Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override ToString in NUnit without access to source code

Tags:

c#

nunit

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

like image 204
RichK Avatar asked Jul 13 '16 12:07

RichK


People also ask

Can we override ToString () method in C#?

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.

What would happen if you will not override the ToString () method?

toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.

What does ToString () do in C#?

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.

How do I create a ToString method in Visual Studio?

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.


1 Answers

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.

like image 148
Charlie Avatar answered Sep 20 '22 04:09

Charlie