JUnit使用Mockito测试异步方法

zc0qhyus  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(131)

我已经使用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构建中,我注意到NullPointercept被抛出:

[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()调用是异步的这一事实有关。
任何帮助都将不胜感激。

vs3odd8k

vs3odd8k1#

解决方案是添加一个带有超时和检查的Mockito验证步骤,以确保模拟组件的方法被调用了适当的次数:

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

字符串

相关问题