Search code examples
javajunit4

JUnit switch from Suite to AllTests causes annotations to not be run


Previously I used Suite.class to specify tests to run for certain suite with following scheme of structure: Suite

@RunWith(Suite.class)
@SuiteClasses({TC0.class, TC1.class...})
public class mainTester {
    @BeforeClass
    public static void setUp() {//create xml report - create file, start xml structure}
    @AfterClass
    public static void tearDown(){//close xml report - close xml structure, close writer
}

Tests

@RunWith(Parameterized.class)
public class TC0 extends testXMLReporter{
    //Tests with params
}

and lastly testXMLReporter holding rule

@Rule
public TestRule watchman = new TestWatcher(){
    //@Override apply, succeeded, failed to write custom xml structure for xml report
}

But since now I need to create suites dynamically reading data from file I switched from Suite.class to AllTests.class. The only thing to make it work was to change my Suite - removing @SuiteClasses - changing @RunWith value to AllTests.class - and adding suite() method

public static TestSuite suite() {
    TestSuite suite = new TestSuite();
    for(Class<?> klass : CsvParser.readCSV()) {
        suite.addTest(new junit.framework.JUnit4TestAdapter(klass));
    }
    return suite;
}

Runs like charm in terms of reading file and running tests but now all of the sudden my @Before/AfterClass annotations as well as @Rule is not running (my report is no longer created). What is the reason for that and how can I fix it?


Solution

  • Finally I gave up using exclusively AllTests.class and now use Suite.class to call AllTests.class. Example:

    main

    Result result = JUnitCore.runClasses(intercessor.class);
    

    intercessor

    @RunWith(Suite.class)
    @SuiteClasses({mainTester.class})
    public class intercessor {
        //do Before & After
    }
    

    mainTester

    @RunWith(AllTests.class)
    public class mainTester {
    
        public static TestSuite suite() {
            TestSuite suite = new TestSuite();
    
            for(Class<?> klass : CsvParser.readCSV()) {
                suite.addTest(new junit.framework.JUnit4TestAdapter(klass));
            }
    
            return suite;
        }
    
    }
    

    Hope it helps somebody in the future