gpt4 book ai didi

Java junit 断言抛出了异常

转载 作者:行者123 更新时间:2023-12-01 19:40:09 25 4
gpt4 key购买 nike

一个比另一个更好吗?如果是这样,原因是什么?我倾向于第一个,因为我可以更快地理解测试的目的。

如果是这样,什么时候应该使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com