junit conditional teardown

2k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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.