在@SpringBootTest中测试@Async带注释的方法 [英] Testing @Async annotated method in @SpringBootTest

查看:144
本文介绍了在@SpringBootTest中测试@Async带注释的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务SomeService,其中有一种方法可以执行一些逻辑.

I have a service SomeService with one method to do some logic.

@Override
public CompletableFuture<Boolean> process(User user) {
    Objects.requiredNonNull(user, "user must not be null");
    // other logic...
}

然后我对此进行测试.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SomeService.class })
public class SomeServiceTest {
    @Autowired private SomeService tested;
    @Test
    public void user_null_expect_NullPointerException() {
        assertThatThrownBy(() -> tested.process(null))
                .isInstanceOf(NullPointerException.class)
                .hasMessage("user must not be null");
    }
}

在我决定使该方法异步之前,它一直运行良好.

It worked fine until I decided to make that method asynchronous.

@Async
@Override
public CompletableFuture<Boolean> process(User user) {
    Objects.requiredNonNull(user, "user must not be null");
    // other logic...
}

因此,由于Spring代理服务器,因此现在不起作用.有谁知道如何配置测试才能使其再次正常工作?

So, now it doesn't work because of Spring proxies. Does anyone have an idea how I must configure my test to make it work again?

推荐答案

好的,我有一个解决方案.问题不在异步方法中,问题在于错误的断言.我不知道AssertJ能够测试CompletableFuture.

Ok, I have a solution. The problem is not in async method, the problem is in wrong assertions. I didn't know AssertJ is able to test CompletableFuture.

所以我的解决方法是这样:

So my solution is this:

@Test
public void user_null_expect_NullPointerException() {
    final CompletableFuture<Boolean> result = getCompletedResult(null);

    assertThat(result)
            .isCompletedExceptionally()
            .hasFailedWithThrowableThat()
            .isInstanceOf(NullPointerException.class)
            .hasMessage("user must not be null");
}

private CompletableFuture<Boolean> getCompletedResult(User user) {
    final CompletableFuture<Boolean> result = tested.process(user);
    await().atMost(10, TimeUnit.SECONDS).until(result::isDone);
    return result;
}

如果您有更好的解决方案,请告诉我.

If you have a better solution, let me know.

这篇关于在@SpringBootTest中测试@Async带注释的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆