junit conditional teardown

别说谁变了你拦得住时间么 提交于 2019-12-01 21:53:18

问题


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

is such a scenario possible using junit?


回答1:


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");
    }
}

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.



来源:https://stackoverflow.com/questions/8118079/junit-conditional-teardown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!