How to use JUnit to test asynchronous processes

前端 未结 18 1646
小蘑菇
小蘑菇 2020-11-29 15:06

How do you test methods that fire asynchronous processes with JUnit?

I don\'t know how to make my test wait for the process to end (it is not exactly a unit test, it

18条回答
  •  时光说笑
    2020-11-29 15:35

    If you use a CompletableFuture (introduced in Java 8) or a SettableFuture (from Google Guava), you can make your test finish as soon as it's done, rather than waiting a pre-set amount of time. Your test would look something like this:

    CompletableFuture future = new CompletableFuture<>();
    executorService.submit(new Runnable() {         
        @Override
        public void run() {
            future.complete("Hello World!");                
        }
    });
    assertEquals("Hello World!", future.get());
    

提交回复
热议问题