使用Mockito进行JUnit异步方法测试

9

我使用Spring Framework(版本5.0.5.RELEASE)在Java 1.8类中实现了一个异步方法:

public class ClassToBeTested {
    @Autowired
    private MyComponent myComponent;

    @Async
    public void doStuff(List<MyClass> myObjects) {
        CompletableFuture<MyResponseObject>[] futureList = new CompletableFuture[myObjects.size()];
        int count = 0;

        for (MyClass myObject : myObjects) {
            futureList[count] = myComponent.doOtherStuff(myObject);
            count++;
        }

        // Wait until all doOtherStuff() calls have been completed
        CompletableFuture.allOf(futureList).join();

        ... other stuff ...
    }
}

我想使用JUnit和Mockito测试这个类。我已经进行了如下设置,目的是模拟对组件中doStuff()方法的调用:

@MockBean
private MyComponent myComponentAsAMock;

@InjectMocks
@Autowired
private ClassToBeTested classToBeTested;

@Test
public void myTest() throws Exception {
    // Create object to return when myComponent.doOtherStuff() is called.
    CompletableFuture<MyResponseObject> completableFuture = new CompletableFuture<MyResponseObject>();
    ... populate an instance of MyResponseObject ...
    completableFuture.complete(myResponseObject);

    // Return object when myComponent.doOtherStuff() is called.
    Mockito.when(
        myComponentAsAMock.doOtherStuff(ArgumentMatchers.any(MyClass.class)))
        .thenReturn(completableFuture);

    // Test.
    List<MyClass> myObjects = new ArrayList<MyClass>();
    MyClass myObject = new MyClass();
    myobjects.add(myObject);
    classToBeTested.doStuff(myObjects);
}

当我在Eclipse中单独运行单元测试时,它似乎很成功,但是在进行整个项目的Maven构建时,我注意到会抛出NullPointerException异常:

[ThreadExecutor2] .a.i.SimpleAsyncUncaughtExceptionHandler : Unexpected error occurred invoking async method 'public void package.ClassToBeTested.doStuff(java.util.List)'.

java.lang.NullPointerException: null
at java.util.concurrent.CompletableFuture.andTree(CompletableFuture.java:1306) ~[na:1.8.0_131]
at java.util.concurrent.CompletableFuture.allOf(CompletableFuture.java:2225) ~[na:1.8.0_131]
at package.ClassToBeTested.doStuff(ClassToBeTested.java:75) ~[classes/:na]

错误发生在ClassToBeTested.java的这一行上:
CompletableFuture.allOf(completedFutureList).join();

看起来异常消息是在测试完成后显示在Maven构建输出中的(还有其他测试正在运行,其输出会在错误消息之前出现),所以我猜测这与调用doStuff()是异步的事实有关。

任何帮助都将不胜感激。

1个回答

36
解决方案是在Mockito的验证步骤中添加超时和检查,以确保被模拟组件的方法已被适当地调用了指定次数:

解决方案是在Mockito的验证步骤中添加超时和检查,以确保被模拟组件的方法已被适当地调用了指定次数:

    Mockito.verify(myComponentAsAMock, Mockito.timeout(1000).times(1)).doOtherStuff(ArgumentMatchers.any(MyClass.class));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接