JUnit conditional disassembly

I want conditional disassembly in my JUnit test cases, such as

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

I want to have a condition like this

if(pass) 
then execute teardown 
else skip teardown

Is it possible to use JUnit in such a scenario?

Solution

You can do this using testrule Testrule allows you to execute code before and after testing methods If the test throws an exception (or assertionerror with failed assertion), the test fails, and you can skip teardown() An example is:

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

Please note that you call teardown manually, so you don't want to use the @ after annotation on the method, otherwise it will be called twice For more examples, see externalresource Java and expectedexception java.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>