我想在我的项目中使用RxJava并编写简单的异步方法,现在我尝试测试它。我无法使用Executor对其进行测试,因为我得到了结果:java.lang.AssertionError: Not completed! (0 completions)
服务方式:
@Override
public Observable<User> addOrderAsynchronously(String username, Order order) {
if (username != null && order != null) {
return Observable
.fromCallable(() -> userRepository.findByUsername(username))
.filter(Objects::nonNull)
.map(user -> {
synchronized (this) {
user.getOrders().add(order);
order.setUser(user);
}
return user;
})
.map(userRepository::save);
}
return Observable.empty();
}
没有执行者的工作测试:
@Test
public void shouldSaveUserSynchronouslyTest() throws Exception {
// given
TestSubscriber<User> subscriber = new TestSubscriber<>();
final Order order = new Order();
final User user = new User();
when(userRepository.findByUsername(user.getUsername()))
.thenReturn(user);
when(userRepository.save(any(User.class)))
.thenReturn(user);
// when
userService.addOrderAsynchronously(user.getUsername(), order)
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
assertThat(subscriber.getOnNextEvents()).isEqualTo(Collections.singletonList(user));
}
现在我想用执行者测试:
@Test
public void shouldSaveUserSynchronouslyTest() throws Exception {
// given
TestSubscriber<User> subscriber = new TestSubscriber<>();
final Order order = new Order();
final User user = new User();
when(userRepository.findByUsername(user.getUsername()))
.thenReturn(user);
when(userRepository.save(any(User.class)))
.thenReturn(user);
// when
userService.addOrderAsynchronously(user.getUsername(), order)
.subscribeOn(Schedulers.from(executor))
.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
assertThat(subscriber.getOnNextEvents()).isEqualTo(Collections.singletonList(user));
}
此测试无效,因为我得到结果java.lang.AssertionError: Not completed! (0 completions)
。
执行者来自@Bean方法:
@Bean
public Executor executor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(500);
executor.initialize();
return executor;
}
如何用执行程序编写单元测试?