java - 在@SpringBootTest中测试@Async注释的方法

标签 java spring-boot unit-testing asynchronous assertj

我有一个服务 SomeService,它有一种方法来执行一些逻辑。

@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");
    }
}

它工作得很好,直到我决定使该方法异步。

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

所以,现在由于 Spring 代理,它不起作用。 有谁知道我必须如何配置我的测试才能使其再次工作?

最佳答案

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

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

@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;
}

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

关于java - 在@SpringBootTest中测试@Async注释的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869463/

相关文章:

java - Spring boot POST PDF内容类型'application/pdf不支持

SpringBoot - 解析 HTTP 请求 header 时出错(Oauth2 https 端点)

c++ - 获取所有 boost 测试套件/测试用例

unit-testing - 单元测试是否适合短期类(class)

java - 无法解析符号

Java keytool错误: java. lang.Exception : Input not an X. 509证书

java - 使用 Struts 2 输出时出现 JSON 异常错误

java - 更新 Spring Boot Parent 后的 PortUnreachableExceptions 垃圾邮件日志

java - 从 Java 运行 Ruby 命令行应用程序

java - 根据某些规则分割字符串