提问人:divad 提问时间:11/8/2022 最后编辑:divad 更新时间:11/9/2022 访问量:443
在 spring webflux 应用程序的单元测试中模拟存储库时出错(使用 JUnit 和 Mockito)?
Error when mocking a repository in unit test of a spring webflux application (using JUnit and Mockito)?
问:
我还没有找到解决这个问题的方法。
我的测试类:
@WebFluxTest(controllers = {PatronController.class})
@Import({PatronService.class}) //to satisfy PatronController dependency.
@ExtendWith({PatronParameterResolver.class})
class PatronFunctionsSpec {
private Patron patron;
private Mono<Patron> patronMono;
private final PatronService patronService = Mockito.mock(PatronService.class);
@MockBean
private PatronRepository patronRepository;
@Autowired
private WebTestClient client;
@BeforeEach
void init(Patron injectedPatron) {
patron = injectedPatron;
patronMono = Mono.just(patron);
}
//Patron Story: patron wants to create an account with us
@Nested
@DisplayName("Creating a patron.")
class CreatingPatron {
@Test
@DisplayName("PatronService.create() returns success msg in Response obj after creating patron.")
void getResponseObjFromServiceCreate() {
Flux<Patron> patronFlux = Flux.from(patronMono);
Mockito.when(patronRepository.saveAll(patronMono)).thenReturn(patronFlux);
PatronService patronService = new PatronService(patronRepository);
Mono<Response> responseStream = patronService.create(Mono.just(patron));
Mono<Response> expectedResponseStream = Mono.just(new Response("Welcome, patron. Can't show emojis yet -- sorry."));
assertEquals(expectedResponseStream, responseStream);
}
}
}
请参阅我的 PatronService 类及其代码:
@Service
public class PatronService {
private final PatronRepository patronRepository;
public PatronService(PatronRepository patronRepository) {
this.patronRepository = patronRepository;
}
/**
*
* persists patron via PatronRepo
*/
public Mono<Response> create(Mono<Patron> patronMono) {
patronRepository.saveAll(patronMono).subscribe();
return Mono.just(new Response("Welcome, patron. Can't find the emojis yet -- sorry."));
}
}
我正在测试 PatronService 的 create(),因此需要分别模拟和存根 PatronRepository 及其函数。但问题是:运行测试用例后,我得到这个异常: java.lang.NullPointerException:无法调用“reactor.core.publisher.Flux.subscribe()”,因为“patronFlux”为空 在 com.budgit.service.PatronService.create(PatronService.java:26)
我该如何解决这个问题?
答: 暂无答案
评论
subscribe
null