This is how I handle exceptions in unit tests:
If you do not explicitly check the exception, you should add a throw clause for the method - if the exception was thrown and you did not expect its throw, then the test failed. eg.
@Test public void testFooNormal() throws DBException{ String key = "test"; String value = "expected"; daoClass daoMock = createMock(daoClass.class); expect(daoMock.lookup(key)).andReturn(value);
If you explicitly check for an exception, add a try-catch around the line from which you expect it to be selected (select the narrowest version of Exception that you expect), and then set the boolean value in the catch clause and approve it should be boolean. eg.
@Test public void testFooError(){ String key = "test"; String value = "expected"; boolean exceptionThrown = false; daoClass daoMock = createMock(daoClass.class); try{ expect(daoMock.lookup(key)).andReturn(value); }catch (DBException e) { exceptionThrown = true; }
This is a good way to check for exceptions because it means that you are checking not only that the correct exception has been selected, but also that it is thrown from exactly the line you expect. If you use @test (expected = ...), then another line in the test may throw this exception, and the test may fail.
source share