Handling exceptions
Exception handling is an important part of Java coding. The Java community follows a set of best practices about exception handling. The following are the exception handling best practices for unit testing:
Do not write catch blocks to pass a unit test. Consider the following example where a
Calculator
program has adivide
method. It takes two integers, divides, and returns a result. Whendivide
encounters a divide by zero, the program should throw an exception. The following is the code:public class Calculator { public int divide(int op1, int op2) { return op1/op2; } }
The following is the test:
@Test public void divideByZero_throws_exception() throws Exception { try { calc.divide(1, 0); fail("Should not reach here"); } catch (ArithmeticException e) { } }
Instead of catching
ArithmeticException
, we can apply the JUnit 4 pattern as follows:@Test(expected = ArithmeticException.class) public void divideByZero_throws_exception() throws Exception...