Should I test toString () with junit?

Can such tests have good reason for being?

+7
source share
4 answers

Some classes use toString for more than a user-readable info line. Examples are StringBuilder and StringWriter . In this case, of course, it is advisable to test the method, like any other business value method.

Even in the general case, toString smoking test is a good practice for reliability (exceptions are possible). The last thing you need is a log expression that exploded your code due to poorly implemented toString . This has happened to me several times, and the resulting errors are of the most nasty types, since you do not even see the toString call in the source code - it is implicitly buried inside the log statement.

+22
source

The question is not if I should test toString (), but do you care about the result of toString ()? Is something being used? If yes, then yes, check it out.

If the method is used for something real, check it out.

+4
source

The obvious answer is "no, it's just a waste of time." But for many classes, primarily for value wrappers, toString should be overloaded and provide more information, just org.package.ClassName@2be2befa

So my proposition test for toString:

 @Test public final void testToString() { assertFalse(new MyClass().toString().contains("@")); } 

It also increases test convention, which is at least not bad.

+2
source

If the result of the method is important to you, you should test it, otherwise you can simply ignore it.

0
source

All Articles