Can such tests have a good reason to exist?
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.
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.
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.
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.
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.
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.
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