junit 条件拆卸

2023-12-04

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

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

在拆解中我想要一个像这样的条件

if(pass) 
then execute teardown 
else skip teardown

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


你可以用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 注释,否则它会被调用两次。有关更多示例,请查看外部资源.java and 预期异常.java.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

junit 条件拆卸 的相关文章

随机推荐