How can I run cleanup method only after tagged tests?

arghtype :

I'm writing JUnit 5 tests for my Java project.

I have some test methods that require time consuming clean up (after each of them). Ideally, I would like to mark them with some annotation and run cleanup method only for them.

This is what I tried:

class MyTest {

    @AfterEach
    @Tag("needs-cleanup")
    void cleanup() {
        //do some complex stuff
    }

    @Test
    void test1() {
         //do test1
    }

    @Test
    @Tag("needs-cleanup")
    void test2() {
         //do test2
    }
}

I want cleanup method to be run only after test2. But it actually runs after both tests.

Is it possible to achieve it via some combination of JUnit 5 annotations? I don't want to split my test class into several classes or call cleanup from test methods directly.

MohammadReza Alagheband :

From Documentation:

TestInfo: if a method parameter is of type TestInfo, the TestInfoParameterResolver will supply an instance of TestInfo corresponding to the current test as the value for the parameter. The TestInfo can then be used to retrieve information about the current test such as the test’s display name, the test class, the test method, or associated tags. The display name is either a technical name, such as the name of the test class or test method, or a custom name configured via @DisplayName.

TestInfo acts as a drop-in replacement for the TestName rule from JUnit 4.

Regarding above description, you can use TestInfo class which gives you information of the class that cleanUp is supposed to be run for,then you need check the condition and allow those you want by checking their tags:

@AfterEach 
void afterEach(TestInfo info) {
    if(!info.getTags().contains("cleanItUp")) return; // preconditioning only to needs clean up
        //// Clean up logic Here
}


@Test
@Tag("cleanItUp")
void myTest() {

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115699&siteId=1