How to use JUnit to test asynchronous processes

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

    Let's say you have this code:

    public void method() {
            CompletableFuture.runAsync(() -> {
                //logic
                //logic
                //logic
                //logic
            });
        }
    

    Try to refactor it to something like this:

    public void refactoredMethod() {
        CompletableFuture.runAsync(this::subMethod);
    }
    
    private void subMethod() {
        //logic
        //logic
        //logic
        //logic
    }
    

    After that, test the subMethod this way:

    org.powermock.reflect.Whitebox.invokeMethod(classInstance, "subMethod"); 
    

    This isn't a perfect solution, but it tests all the logic inside your async execution.

提交回复
热议问题