How to use JUnit to test asynchronous processes

前端 未结 18 1640
小蘑菇
小蘑菇 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:54

    There are many answers here but a simple one is to just create a completed CompletableFuture and use it:

    CompletableFuture.completedFuture("donzo")
    

    So in my test:

    this.exactly(2).of(mockEventHubClientWrapper).sendASync(with(any(LinkedList.class)));
    this.will(returnValue(new CompletableFuture<>().completedFuture("donzo")));
    

    I am just making sure all of this stuff gets called anyway. This technique works if you are using this code:

    CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join();
    

    It will zip right through it as all the CompletableFutures are finished!

提交回复
热议问题