【发布时间】:2013-11-19 08:54:39
【问题描述】:
我正在编写一个 JUnit/Mockito 测试,预计会引发异常。我当然可以这样做:
@Test(expected=IllegalArgumentException.class)
但是在它被抛出后它不允许我做任何其他事情。所以我想也许更像:
Exception actualEx = null;
try {
// Act
sut.doStuff();
} catch (final Exception ex) {
actualEx = ex;
}
// Assert
assertTrue(IllegalArgumentException.class.equals(actualEx.getClass()));
// ... perhaps verify the exception details
verifyNoMoreInteractions(mockObject);
这看起来很丑陋,感觉可以改进 - 有没有更好的方法?
【问题讨论】:
-
您尝试过 ExpectedException 规则吗? alexruiz.developerblogs.com/?p=1530
-
或catch-exception,太糟糕了,但是他们使用 FEST-Assert(几乎死了)而不是 AssertJ
-
@Brice 谢谢,但如果我能提供帮助,我宁愿避免使用附加库...
-
我明白(我仍然不喜欢添加第 N 个库),虽然 catch-exception 使我们能够在测试中遵循 Arrange/Act/Assert 或 BDD 原则,这在可读性方面更有趣测试。
-
另一个副本,其答案也涵盖了 JUnit5 的
AssertThrows: How do you assert that a certain exception is thrown in JUnit 4 tests?
标签: java unit-testing exception junit mockito