We have mentioned this before. In Chapter 1, Getting Started with Testing we stated that you should test for exceptions and wrong values instead of just testing positive cases.
We have also presented this test before but here we are digging deeper into it:
public final void testExceptionForLessThanAbsoluteZeroF() { try { TemperatureConverter.fahrenheitToCelsius(TemperatureConverter.ABSOLUTE_ZERO_F-1); fail(); } catch (InvalidTemperatureException ex) { // do nothing } } public final void testExceptionForLessThanAbsoluteZeroC() { try { TemperatureConverter.celsiusToFahrenheit(TemperatureConverter.ABSOLUTE_ZERO_C-1); fail(); } catch (InvalidTemperatureException ex) { // do nothing } }
Every time we have a method that is supposed to generate an exception, we should test this condition. The best way of doing it is by invoking the method inside a try-catch block, catching the expected Exception
, and...