Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I test toString() with junit?

Can such tests have a good reason to exist?

like image 593
AvrDragon Avatar asked Sep 21 '12 10:09

AvrDragon


People also ask

Do we need to call toString method in Java?

Note: In all wrapper classes, all collection classes, String class, StringBuffer, StringBuilder classes toString() method is overridden for meaningful String representation. Hence, it is highly recommended to override toString() method in our class also.

What is toString () and why we need it?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

Does Java automatically use toString?

Every class in Java inherits the default implementation of the toString method. The functionality of the toString method is to return a String representation of the object on which it's called.

Do you have to call toString?

toString() 's default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.


2 Answers

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

Even in the general case it is good practice to smoke-test toString for reliability (no exceptions thrown). The last thing you need is a log statement blowing up your code due to an ill-implemented toString. It has happened to me several times, and the resulting bugs are of the nastiest kind, since you don't even see the toString call in the source code—it's implicitly buried inside a log statement.

like image 169
Marko Topolnik Avatar answered Sep 28 '22 00:09

Marko Topolnik


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

If a method gets used for something real, then test it.

like image 43
Matthew Farwell Avatar answered Sep 28 '22 02:09

Matthew Farwell