junit 有条件的拆解 [英] junit conditional teardown

查看:25
本文介绍了junit 有条件的拆解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 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
}

在拆解中我想要一个像

if(pass) 
then execute teardown 
else skip teardown

使用junit可以实现这样的场景吗?

is such a scenario possible using junit?

推荐答案

您可以使用 TestRule.TestRule 允许您在测试方法之前和之后执行代码.如果测试抛出异常(或断言失败的 AssertionError),则测试失败,您可以跳过 tearDown().一个例子是:

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.javaExpectedException.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆