我有一个 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
方法。这可以做到吗?如果可以,怎么做?
最佳答案
根据您的代码,只有当您能够在此 if
中实现真实条件时,才有可能:
if (condition is not met) {
do something...
throw new Exception();
} else {
do something else;
}
如果由于某些原因你无法在单元测试中准备这种条件(例如,需要互联网连接),你可以将条件检查提取到新方法中:
if (isNotCondition()) {
do something...
throw new Exception();
在测试类中,您重写新方法并返回您想要的内容:
MyService myService = new MyService() {
@Override
boolean isNotCondition() {
return true;
}
}
这是测试异常情况的更紧凑的方法:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testMethod1WhenMethod2ThrowsException() throws Exception {
thrown.expect(Exception.class);
thrown.expectMessage("expected exception message");
myServive.method1();
}
关于java - 正在测试的方法调用 private void 方法,我也想将其包含在我的测试中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573199/