我有一个服务 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/