假设在测试中是:
@Rule
public ExpectedException thrown = ExpectedException.none();
一些测试包含:
thrown.expect(SomeNastyException.class);
现在如果需要更详细地检查这个 SomeNastyException
该怎么办?
当然,可以不使用 ExcectedException
并用 try/catch 包装调用,然后以任何需要的方式检查异常,但现在的问题是关于是否可以通过 ExpectedException
来完成,例如:
assertEquals("42", thrown.getException().getUniversalAnswerToEverything());
最佳答案
该规则中有一个不太专业的 expect
方法版本,它接受 Hamcrest 的匹配器:
如果有一个 Matcher
实现,此方法将允许您断言几乎所有有关抛出的异常的内容。
例如,对于您的情况,它看起来像这样:
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
....
exceptions.expect(hasProperty("UniversalAnswerToEverything", is(42)));
Hamcrest 有一个非常灵活的匹配器模型,因此如果您对库中包含的内容不满意,您也可以轻松编写自己的匹配器模型。
关于java - 是否可以使用 JUnit Rule ExpectedException 访问异常 "catched"的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59946794/