Update: JUnit5 has an improvement for exceptions testing: assertThrows
.
The following example is from: Junit 5 User Guide
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
Original answer using JUnit 4.
There are several ways to test that an exception is thrown. I have also discussed the below options in my post How to write great unit tests with JUnit
Set the expected
parameter @Test(expected = FileNotFoundException.class)
.
@Test(expected = FileNotFoundException.class)
public void testReadFile() {
myClass.readFile("test.txt");
}
Using try
catch
public void testReadFile() {
try {
myClass.readFile("test.txt");
fail("Expected a FileNotFoundException to be thrown");
} catch (FileNotFoundException e) {
assertThat(e.getMessage(), is("The file test.txt does not exist!"));
}
}
Testing with ExpectedException
Rule.
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testReadFile() throws FileNotFoundException {
thrown.expect(FileNotFoundException.class);
thrown.expectMessage(startsWith("The file test.txt"));
myClass.readFile("test.txt");
}
You could read more about exceptions testing in JUnit4 wiki for Exception testing and bad.robot - Expecting Exceptions JUnit Rule.
org.mockito.Mockito.verify
with various parameters to make sure that certain things happened (such that a logger service was called with the correct parameters) before the exception was thrown. – Tracheo