3

我想在我的 junit 测试用例中进行有条件的拆解,例如

@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}

在拆解中我想要一个条件

if(pass) 
then execute teardown 
else skip teardown

使用junit可以实现这种情况吗?

4

1 回答 1

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.javaExpectedException.java

于 2011-11-14T09:26:46.390 回答