JUnit test not executing all threads created within the test
JUnit is exiting the test method early. You need to wait for all of the threads to complete before you exit the testCalculator()
method.
An easy way to do that is by using a CountDownLatch
.
Initialize a
CountDownLatch
withCountDownLatch latch = new CountDownLatch(20)
.Pass each
Calculator
runnable a reference to the latch. At the end of therun()
method, calllatch.countDown()
.At the end of the
testCalculator()
method calllatch.await()
. This will block untillatch.countDown()
has been called 20 times (i.e. when all threads have completed).
Your test method finishes before all the spawned threads are finished. When the JUnit executor finishes, all spawned threads are killed.
If you want to run this kind of test, you should keep a collection of the threads you have created and join()
each of them at the end of your test method. The calls to join()
each thread are executed in a second loop (following the loop that starts all the threads).
Something like this:
@Testpublic void testCalculator() { List<Thread> threads = new ArrayList<>(); for (int i = 1; i < 21; i++) { calculator = new Calculator(i); thread = new Thread(calculator); threads.add(thread); System.out.println(thread.getName() + " Created"); thread.start(); System.out.println(thread.getName() + " Started"); } for (Thread thread : threads) { thread.join(); } }
If you want to have the threads all start around the same time (e.g., if your loop that is creating the threads does some non-trivial work each time through the loop):
@Testpublic void testCalculator() { List<Thread> threads = new ArrayList<>(); for (int i = 1; i < 21; i++) { threads.add(new Thread(new Calculator(i))); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); }}