I need a test case for the exception part:
try {
return String.valueOf(value);
} catch (Exception e) {
return null;
}
I need a test case for the exception part:
try {
return String.valueOf(value);
} catch (Exception e) {
return null;
}
You can create a class whose toString()
method throws an exception:
class Throwing {
@Override public String toString() {
throw new UnsupportedOperationException();
}
}
and then pass an instance of this to your method in the unit test:
assertNull(yourMethod(new Throwing()));
Of course, you can use your favorite mocking framework rather than creating an explicit class like this.
But think very carefully about whether this method is worthwhile. It is a pretty big source of problems if you have classes whose toString()
methods throw exceptions, and that's the only case that your method handles over and above String.valueOf
.
In any other place in the code where you happen to perform a string conversion (e.g. "" + instance
), instances of that class will throw an exception, and you won't be catching them there.
Consider this insidious case:
try {
doSomething(instance);
} catch (Exception e) {
throw new RuntimeException("Exception occurred: " + instance, e);
}
In this case, the exception from instance.toString()
would only be thrown if an exception e
is caught, but it's the exception from toString()
which would be thrown - you'd not actually see e
at all. Thus, it would make it much harder to see the real problem.
I would recommend not having this method at all, so not catching the exception, and using String.valueOf(Object)
directly (or implicitly), so that you actually know when a problem occurs.
Unchecked exceptions - the only type which can be thrown by toString()
- indicate programming errors. Don't swallow those errors, then you'll know to fix them.