我希望在我的junit测试用例中有条件拆解,比如
@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}
在拆解中我希望有一个像
这样的条件if(pass)
then execute teardown
else skip teardown
是否可以使用junit?
答案 0 :(得分:7)
您可以使用TestRule执行此操作。 TestRule
允许您在测试方法之前和之后执行代码。如果测试抛出异常(或者断言失败的AssertionError),则测试失败,您可以跳过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注释,否则会调用两次。有关更多示例,请查看ExternalResource.java和ExpectedException.java。