JUnit terminates child threads

前端 未结 6 824
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 13:04

When I test the execution of a method that creates a child thread, the JUnit test ends before the child thread and kills it.

How do I force JUnit to wait for the chil

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 13:23

            while (s.isRunning()) {
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    

    You could try to block the JUnit thread and have it wait for your thread to complete. The Thread.sleep() is needed so that your thread does not hog CPU. In this example s would be your thread you will need to have an isRunning() method so you can check if the thread is still running every SLEEP_TIME milliseconds. I know this isn't the greatest solution but if you only have 2 threads and you dont want JUnit killing your thread this works. The while loop with cause this JUnit thread to stay alive and wait for your other thread to finish.

提交回复
热议问题