【问题标题】:How to test exception is thrown with Junit [duplicate]如何使用 Junit 测试异常 [重复]
【发布时间】:2017-09-22 10:30:05
【问题描述】:

我想知道如何编写单元测试来获取以下方法的 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;
    }
}

【问题讨论】:

  • 这个 getUpdatedJWTToken 在你的代码中在哪里?

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


【解决方案1】:

如果在单元测试之前没有捕获到异常,您可以检查可抛出的异常。在您的情况下,您无法检查UnsupportedEncodingException,但可以检查IllegalStateException

单元测试必须如下所示:

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

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

【讨论】:

    【解决方案2】:

    你可以像这样使用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();
         }
     }
    

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 2018-07-20
      • 2016-12-07
      • 2013-11-01
      • 1970-01-01
      • 2011-05-28
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多