junit有条件的拆解 [英] junit conditional teardown
问题描述
我想在我的junit测试用例中进行有条件的拆卸,例如
I want to have a conditional teardown in my junit test cases, something like
@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}
在拆解中,我希望有类似
in teardown i want to have a condition like
if(pass)
then execute teardown
else skip teardown
使用junit可以实现这种情况吗?
is such a scenario possible using junit?
推荐答案
You can do this with a TestRule. TestRule
allows you to execute code before and after a test method. If the test throws an exception (or AssertionError for a failed assertion), then the test has failed, and you can skip the tearDown(). An example would be:
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 .
Note that you're calling tearDown manually, so you don't want to have the @After annotation on the method, otherwise it gets called twice. For more examples, look at ExternalResource.java and ExpectedException.java.
这篇关于junit有条件的拆解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!