LoginSignup
51
42

More than 5 years have passed since last update.

JUnitでの例外テストの書き方

Posted at

アノテーション利用

  @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
  }
51
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
42