Search code examples
javajunittheory

How to Clear instance filed afterClass in Junit?


I am looking a way to collect and publish these myResults. But Junit @AfterClass only supports static method.

If I am having a super class If multiple test cases are running it can be ugly. Any idea how I can resolve this? If I use after, I won't get the full output collected by myresult

abstract class MainTestCase{
  static List<String> myResults = new ArrayList();

  @AfterClass public static void WrapUp() {

    //code to write the myResults to text file  goes here
    System.out.println("Wrapping Up");
    myResults.clear()
  }

}

@RunWith(Theories.class)
public class TheoryAfterClassTest extends MainTestCase {

  @DataPoint
  public static String a = "a";

  @DataPoint
  public static String b = "bb";

  @DataPoint
  public static String c = "ccc";

  @Theory
  public void stringTest(String x, String y) {
    myResults.add(x + " " + y);
    System.out.println(x + " " + y);
  }      
}

Solution

  • Putting List<String> myResults; into a ThreadLocal may solve the problem, this how all your parallel test cases would have their own instance of myResults.

    static ThreadLocal<List<String>> myResults = new ThreadLocal<>();
    
    @BeforeClass
    public static void setUpClass() {
        myResults.set(new ArrayList<String>());
    }
    
    // use it later in your code
    @Test
    public void myTestCase() {
         myResults.get().add("result");
    }