I'm trying to test a method that does it's work in a separate thread, simplified it's like this:
public void methodToTest()
{
Thread thread = new Thread()
{
@Override
public void run() {
Clazz.i = 2;
}
};
thread.start();
}
In my unit test I want to test that Clazz.i == 2, but I can't do this because I think that the assert is run before the thread changes the value. I thought of using another thread to test it and then use join to wait but it still doesn't work.
SSCCE:
@Test
public void sscce() throws InterruptedException
{
Thread thread = new Thread()
{
@Override
public void run() {
methodToTest()
}
};
thread.start();
thread.join();
AssertEquals(2, Clazz.i);
}
public static class Clazz
{
public static int i = 0;
}
I think this is because the test main code creates a thread that is waiting (joined) to the 2nd thread, but the 2nd thread doesn't do the work, it creates another thread to do the work and then finishes, which continues the first thread, while the third thread does the Clazz.i = 2
after the assertion.
How can I make it so that the first thread waits for the thread that it starts as well as any threads that that thread starts?