user1329339
user1329339

Reputation: 1335

Adding tear down method to junit test suite after loading class dynamically

I load all test dynamically in to a test suite like this:

@RunWith(AllTests.class)
public final class MyTestSuite {
    public static TestSuite suite() {               
        TestSuite suite = new TestSuite();
        for (Test test : findAllTestCasesRuntime()) { // returns a list of JUnit4TestAdapter(Class.forName(fileName))
          suite.addTest(test);
        }    
        return suite;
      }
}

I would like to add a @after method to the testsuite that is run for all tests. Today each test has this method doing the exact same thing. I have tried to subclass testsuite and add an @after method but with no luck.

Upvotes: 0

Views: 359

Answers (1)

user1329339
user1329339

Reputation: 1335

This is the solution I found: I created a base test class:

@Ignore
public class MyTestBase {
    @After
    public void runsAfterEveryTestFromBaseClass() {
        //code
    }   
}

My actual test class now extends this class so the code in the question now looks like this:

@RunWith(AllTests.class)
public final class MyTestSuite extends MyTestBase{
    public static TestSuite suite() {               
        TestSuite suite = new TestSuite();
        for (Test test : findAllTestCasesRuntime()) { // returns a list of JUnit4TestAdapter(Class.forName(fileName))
          suite.addTest(test);
        }    
        return suite;
      }
}

Now the code in the runsAfterEveryTestFromBaseClass method runs after every test.

Upvotes: 1

Related Questions