Junit如何测试异常

时间:2017-09-22 10:30:06

标签: java unit-testing exception junit try-catch

我想知道如何编写单元测试来获取以下方法的catch块。 FOM.create(data)是一种静态方法。

  public String getValue(Data data) {
      try {
          return FOM.create(data);
      } catch (UnsupportedEncodingException e) {
          log.error("An error occured while creating data", e);
          throw new IllegalStateException(e);
      }
  }

目前这是我的单元测试,但它没有点击catch块:

@Test (expected = UnsupportedEncodingException.class)
public void shouldThrowUnsupportedEncodingException() {
    doThrow(UnsupportedEncodingException.class).when(dataService).getUpdatedJWTToken(any(Data.class));
    try {
        dataService.getValue(data);
    }catch (IllegalStateException e) {
        verify(log).error(eq("An error occured while creating data"), any(UnsupportedEncodingException.class));
        throw e;
    }
}

2 个答案:

答案 0 :(得分:0)

如果在单元测试之前未捕获异常,则可以检查throwable异常。在您的情况下,您无法检查UnsupportedEncodingException,但可以检查IllegalStateException

单元测试必须如下:

@Test (expected = IllegalStateException.class)
public void shouldThrowIllegalStateException() {      
    dataService.getValue(data);
}

如果您想检查UnsupportedEncodingException,则必须测试FOM.create(data)方法

答案 1 :(得分:0)

您可以使用 JUnit 的例外规则:

 public class SimpleExpectedExceptionTest {
     @Rule
     public ExpectedException thrown= ExpectedException.none();

     @Test
     public void throwsExceptionWithSpecificType() {
         thrown.expect(NullPointerException.class);
         thrown.expectMessage("Substring in Exception message");
         throw new NullPointerException();
     }
 }