I have a couple of junit test cases where I am calling a method doComplexOperation()
that starts a new thread and prints 0-5 with 100ms sleep in each loop.
When I run each of the test method individually, they all produce different results:
- main method -> prints 0-5
- test1-> print 0 OR doesn't print anything at all
- test2-> prints 0-3
- test3-> prints 0-5
In all these tests the main thread doesn't wait for the thread created in doComplexOperation
to finish. I am expecting similar output when running the main()
method or the @Tests
Is there a configuration on JUnit so that I can have all these tests print 0-4?
import org.junit.jupiter.api.Test;
class Tests {
public static void main(String[] args) {
doComplexOperation();
}
@Test
void test1() {
doComplexOperation(); //Prints 0 OR doesn't print anything at all
}
@Test
void test2() {
doComplexOperation(); //Prints 0 - 3
sleep(300);
}
@Test
void test3() {
doComplexOperation(); //Prints 0 - 4
sleep(1000);
}
static void doComplexOperation() {
new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "-" + i);
sleep(100);
}
}).start();
}
static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}