Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test a blocking method using junit

I have a class with a method that blocks and would like to validate that it is blocking. The method is as shown below.

 public static void main(String[] args) {

    // the main routine is only here so I can also run the app from the command line
    applicationLauncherInstance.initialize();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            if (null != application) {
                applicationLauncherInstance.terminate();
            }
        }
    });

    try {
        _latch.await();
    } catch (InterruptedException e) {
        log.warn(" main : ", e);
    }
    System.exit(0);
}

How can I write a unit test for such a method. I am stuck before starting.

public class ApplicationLauncherTest extends TestCase {


    public void testMain() throws Exception {
        ApplicationLauncher launcher = new ApplicationLauncher();
    }
}
like image 355
Bwire Avatar asked Feb 11 '23 01:02

Bwire


1 Answers

Thanks to Kulu, I found the solution.

public void testMain() throws Exception {
    Thread mainRunner = new Thread(() -> {
        ApplicationLauncher.main(new String[]{});
    });

    mainRunner.start();

    Thread.sleep(5000);

    assertEquals(Thread.State.WAITING, mainRunner.getState());
    mainRunner.interrupt();
}
like image 139
Bwire Avatar answered Feb 13 '23 06:02

Bwire