Objects used in static methods have to be created within the control flow of the same method after the invocation of the method. Otherwise you risk running into race conditions where several threads modify the same object used by the static method. To test this you can do the following.
- Write a test case for the static method in your unit test class
private void testMyStaticMethod(Object parameter) {
ClassUnderTest.myStaticMethod(parameter);
assertTrue(<something>);
}
- Create a client class that runs this test within your unit test class
private class MyStaticMethodClient extends Thread {
private final Object parameter;
public MyStaticMethodClient(String parameter) {
this.parameter = parameter;
}
public void run() {
try {
testMyStaticMethod(parameter);
} catch (Throwable t) {
// just calling the fail() method here is not enough because this is executed in another thread
concurrencyError = t;
}
}
}
- Store the state of the test in a member variable within your unit test class
private Throwable concurrencyError = null;
- Call the static method concurrently from your unit test class
@Test
public void testMyStaticMethodConcurrently() {
for (int i = 1; i < 10; i++) {
if (concurrencyError != null) break;
MyStaticMethodClient clientA = new MyStaticMethodClient(TEST_PARAMETER);
MyStaticMethodClient clientB = new MyStaticMethodClient(TEST_PARAMETER);
clientA.start();
clientB.start();
try {
clientA.join();
clientB.join();
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
assertNull("Concurrently executing the tested method failed with " + concurrencyError, concurrencyError);
}
Comments (0)
You don't have permission to comment on this page.