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?

Shekhar Rai
  • 2,008
  • 2
  • 22
  • 25
Sinny
  • 167
  • 1
  • 10
  • 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? – Kayaman Oct 23 '19 at 10:31
  • Possible duplicate of [JUnit terminates child threads](https://stackoverflow.com/questions/2836885/junit-terminates-child-threads) – Joe Oct 23 '19 at 11:15
  • Possible [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-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. – Solomon Slow Oct 23 '19 at 13:27

0 Answers0