アノテーション利用
@Test(expected = SampleException.class)
public void throwsSampleException() {
// do something
}
try/catchでの書き方
@Test
public void throwsSampleException() {
try {
// do something
...
fail();
} catch (SampleException expected) {
assertThat(expected.getMessage(), equalTo("exception message"));
}
}
Ruleを使った書き方
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void exceptionRule() {
thrown.expect(SampleException.class);
thrown.expectMessage("exception message");
// do something
}