一个比另一个更好吗?如果是这样,原因是什么? 我倾向于第一个,因为我可以更快地理解测试的目的。
如果是这样,什么时候应该使用 assertThrows()
?
@Test(expected=CustomException.class)
public void test_one() {
execute()
}
对比
@Test
public void test_one() {
assertThrows(CustomException.class, () -> execute());
}
最佳答案
假设您这样进行测试:
@Test
public void test_one() {
execute1();
execute2()
}
假设您要检查由execute2()抛出的CustomException
。
现在,如果您采用第一种方法,并且 execute1()
抛出 CustomException
测试仍然会通过,您将无法知道它是否被抛出是否通过execute2()
。
但使用第二种方法,您可以指定要确保 execute2()
方法调用引发异常,因此只有在 CustomException
发生时测试才会通过由 execute2()
方法抛出。
关于Java junit 断言抛出了异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624511/