Suppose I have one test class with three test methods. The tests may either run serially or in two separate threads. Each test method requires its own instance of a collaborator (such as a resource of some kind). However, this would not seem to cut it:
public class MyTestClass {
private Resource resource;
@BeforeMethod public void setupResource() {}
@AfterMethod public void tearDownResource() {}
@Test public void testMethod1() {}
@Test public void testMethod2() {}
@Test public void testMethod3() {}
}
This seems to work when run serially, but if we run the three test methods in parallel (with method granularity), it would seem that because all three tests are invoked via the same instance, the resource
variable ends up being overwritten repeatedly.
So, how about this:
public class MyTestClass {
private static ThreadLocal<Resource> resource;
@BeforeMethod public void setupResource() {}
@AfterMethod public void tearDownResource() {}
@Test public void testMethod1() {}
@Test public void testMethod2() {}
@Test public void testMethod3() {}
}
This seems plausible, and it looks like it can old up if I throw in @DataProvider
and test listeners as well (provided setupResource()
and tearDownResource()
is properly implemented, so that if there are two threads to run tests on, the third method doesn't have any "leftovers" from the first).
Having said that, it seems quite cumbersome to have a @BeforeMethod
, an @AfterMethod
, and wrapping the collaborator (Resource
) in a ThreadLocal. Is there any other good "test-local" alternatives worthy of consideration?