【发布时间】:2023-03-15 01:36:01
【问题描述】:
我有一个 JUnit,我想用它来测试异常。是这样的:
@Test
public void test1() throws Exception {
boolean testPass;
try {
method1();
testPass = true;
Assert.assertTrue(testPass);
}
catch(Exception e) {
testPass = false;
Assert.assertTrue(testPass);
}
System.out.println("End of test2 Junit");
}
method1()是这样的:
public void method1() throws Exception {
try {
do something....
method2();
} catch (Exception e) {
throw e;
} finally {
do some more...
}
}
对于我想要的,只要考虑method1().,我的测试就很好我的问题是method2() 被method1() 调用并且也可以抛出异常。是这样的:
private void method2() throws Exception {
if (confition is not met) {
do something...
throw new Exception();
} else {
do something else;
}
}
有可能method1() 没有抛出异常,但随后method2() 又抛出了异常。我希望我的测试检查其中一个异常,但我不确定如何将 method2() 纳入我的测试,特别是因为它是 private void 方法。可以这样做吗?如果可以,怎么做?
【问题讨论】:
-
factor method2() into my test是什么意思?是否要测试method2()和method1()的逻辑? -
如果可能的话,我想要的只是在
method1()或method2()中都没有抛出异常时通过 assertTrue 并且如果method1()中抛出异常则失败或method2(). -
在这种情况下,如果
method2()抛出Exception或其任何子类,您的测试将失败。 -
您应该测试 public 接口,而不是私有实现。单元测试应该是黑盒测试,因为测试关注从用户角度发生的事情。既然用户不能调用
method2(),应该没有理由去测试它。测试的存在是为了确保实现给出例外的结果。如果method2()抛出method1()吞下的异常,那么用户首先不应该知道该异常。你为什么要测试它?您是否将method2()的详细信息泄露到method1()的合同中?如果是这样,那就是问题所在。 -
啊,好的。谢谢你。
标签: java exception junit junit4