【问题标题】:What is the best approach to unit test try catch to throw an exception? [duplicate]单元测试 try catch 抛出异常的最佳方法是什么? [复制]
【发布时间】:2020-05-13 09:10:31
【问题描述】:
final GregorianCalendar calendar = new GregorianCalendar();
final XMLGregorianCalendar dt;
try {
    dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
} catch (DatatypeConfigurationException e) {
throw new IllegalArgumentException(e);
} return dt;

【问题讨论】:

  • 这能回答你的问题吗? Try catch in a JUnit test
  • 请提供您想要实现的附加说明(不仅仅是一段代码)。

标签: java spring-boot


【解决方案1】:

假设您的方法签名是XMLGregorianCalendar getCalendar(),您可以编写一个Junit4 库来测试IllegalArgumentException.class 异常,如下所示。

@Test(expected = IllegalArgumentException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
    getCalendar();
}

XMLGregorianCalendar getCalendar() {
        final GregorianCalendar calendar = new GregorianCalendar();
        final XMLGregorianCalendar dt;
        try {
            dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
        } catch (DatatypeConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
        return dt;
    }

对于 Junit 5

@Test
void testGetCalendar() {
  Assertions.assertThrows(IllegalArgumentException.class, () -> {
    getCalendar();
  });

}

【讨论】:

  • Junit5 的预期工作吗?因为使用 5 会很棒。
  • 是的,我用 Junit5 测试代码@MoonMaker 更新了我的答案
  • 阅读此文档 (howtodoinjava.com/junit5/expected-exception-example) 并得到相同的答案,但抱怨 org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be throw, but nothing was throwed:
  • @Test public void whenExceptionThrown_thenExpectationSatisfied() { Assertions.assertThrows(IllegalArgumentException.class, () -> { service.getDateAndTime(); }); }
  • 您的测试方法预期会出错,但 getCalendar 永远不会抛出错误,因此您遇到了异常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2018-04-09
相关资源
最近更新 更多