1

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();
        }
    }

}
gtiwari333
  • 24,554
  • 15
  • 75
  • 102
  • What about using `join()` when you want to wait for the thread to finish? – Progman Aug 25 '19 at 18:59
  • I could do the following. But doComplexOperation is from a third party library in my real code. I was hoping JUnit might have some config `` Thread t = new Thread(() -> {... the code ); t.start(); t.join(); `` – gtiwari333 Aug 25 '19 at 19:05
  • Does the API `doComplexOperation()` allows you somehow to react/act/wait on the created threads? Please edit your question to include a detailed description of your unit test and third party library, how you use it, what the API is (link to documentation?) and what you are trying to do. – Progman Aug 25 '19 at 19:07
  • Also, i think it might be a defect with JUnit becase I expect the same result when running `` doComplexOperation();`` from main method or from a @Test – gtiwari333 Aug 25 '19 at 19:08
  • 1
    You might want to look at https://stackoverflow.com/questions/13550922/why-non-daemon-thread-is-terminating-if-in-junit-test – Progman Aug 25 '19 at 19:15
  • thanks for the pointer, it looks it was a feature not a bug :D – gtiwari333 Aug 25 '19 at 19:21

0 Answers0