junit条件拆卸
我想在我的junit测试用例中有一个条件分解,比如junit条件拆卸,junit,conditional,teardown,Junit,Conditional,Teardown,我想在我的junit测试用例中有一个条件分解,比如 @Test testmethod1() { //condition to be tested } @Teardown { //teardown method here } 在teardown,我想有一个条件,比如 if(pass) then execute teardown else skip teardown 使用junit可以实现这样的场景吗 您可以使用一个测试规则允许您在测试方法之前和之后执行代码。如果测试抛出异常(或失败断言的断
@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}
在teardown,我想有一个条件,比如
if(pass)
then execute teardown
else skip teardown
使用junit可以实现这样的场景吗 您可以使用一个<代码>测试规则允许您在测试方法之前和之后执行代码。如果测试抛出异常(或失败断言的断言错误),则测试失败,您可以跳过tearDown()。例如:
public class ExpectedFailureTest {
public class ConditionalTeardown implements TestRule {
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
tearDown();
} catch (Throwable e) {
// no teardown
throw e;
}
}
};
}
}
@Rule
public ConditionalTeardown conditionalTeardown = new ConditionalTeardown();
@Test
public void test1() {
// teardown will get called here
}
@Test
public void test2() {
Object o = null;
o.equals("foo");
// teardown won't get called here
}
public void tearDown() {
System.out.println("tearDown");
}
}
请注意,您正在手动调用tearDown,因此您不希望在方法上有@After注释,否则它会被调用两次。有关更多示例,请参阅和