Wednesday, September 22, 2010

Expected exceptions in JUnit 4

In Junit 4 we can use the annotation @Test(expected=SomeException.class) to mark that tests should pass when the expected exception is thrown from the test.

The problem with this is that the test will still pass even if the exception is thrown from the wrong place.

JUnit 4.7 addresses this issue by introducing rules. Rules are just another extension mechanism for JUnit. Check how the following code allows us to verify both the type and the message of the exception and, above all, specify where the exception should be raised.

@Rule
public ExpectedException thrown = ExpectedException.none();


    @Test
    public void testRules() throws FileNotFoundException {
        File file = new File("whateverfile");
        thrown.expect(FileNotFoundException.class);
        thrown.expectMessage("(No such file or directory)");
        FileInputStream fis = new FileInputStream(file);

    }

No comments:

Post a Comment