0

When executing a single JUnit test based on nonblocking scheme all the threads are being killed when test method is terminating its scope. For example

@Test public void testMethod() { System.out.println("Before Running Thread"); Runnable runnable = new Runnable() { @Override public void run() { for(int index = 0; index <=1000; index++) { System.out.println("Current index: " + index); } } }; new Thread(runnable).start(); System.out.println("After Running Thread"); } 

Very possible output is :

Before Running Thread Current index: 0 Current index: 1 Current index: 2 Current index: 3 After Running Thread 

Now let us consider a thread being built in @Before method and lets assume that more than one @Test method relies on its activity for example:

class TestSuite { Thread importantThread; @Before public void beforeTest(){ Runnable runnable = new Runnable() { @Override public void run() { for(int index = 0; index <=1000; index++) { System.out.println("Current index: " + index); } } }; importantThread = new Thread(runnable); importantThread.start(); } @Test public void testOne { // Some action } @Test public void testTwo() { // Some action } } 

This test suite will execute the importantThread until the end of execution of the test method that would be executed as last one.

My question is: Is there any warranty that JUnit will not kill the mainThread in-between test methods testOne and testTwo?

3
  • 2
    It's not a very good unit test if it relies on some external thread like that, so even if you can get it to work, you should fix your design instead. What is the thread responsible for, and why does it run inside your test harness? Commented Oct 23, 2019 at 10:31
  • Possible duplicate of JUnit terminates child threads Commented Oct 23, 2019 at 11:15
  • Possible XY problem. You might get more/better help if you can explain why your test needs those threads. Chances are good that somebody can steer you toward a better way of testing or, toward a more testable system design. Commented Oct 23, 2019 at 13:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.