我有一个使用spring webflux和电抗器的休息控制器,我正在为控制器编写单元测试。请在下面的代码段中查找并帮助我编写用于测试.doOnError块的单元测试方法。
我尝试使用Mockito引发异常
doThrow(CriticalException.class) .when(myService).myMethod(object);
This is my unit test
StepVerifier.create(
Mono.just(
webTestClient.post()
.uri("/endpoint")
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(requestJson)) //Set the body of the request to the given synchronous Object
//Returns:a Mono with the response
//Act
.exchange() //Perform the exchange
//Assert
.expectStatus().isOk()
.expectBody(Agreement.class)
.returnResult()
.getResponseBody()))
.expectNextMatches(agreementResponse -> {
assertNotNull(agreementResponse.getAgreementParticipant());
return true;
})
.expectComplete()
.verify();
这是我的控制人
return Mono.fromCallable(() -> {
myService.myMethod(object);
return object;
}).log().subscribeOn(Schedulers.elastic())
.map(p -> ResponseEntity.ok(p))
.defaultIfEmpty(ResponseEntity.notFound().build())
.doOnError(e -> {
LOGGER.error(LOG_FORMAT, e.getMessage(), e.getStackTrace());
});
Mockito is not returning exception while myService.myMethod(object) is been called.
Please suggest proper way to write test for .defaultIfEmpty and .doOnError blocks
答案 0 :(得分:4)
返回CriticalException.class
而不是在模拟myService.myMethod(object)
时抛出exception
例如:
Mono
在下面找到示例代码段
Mockito.doReturn(Mono.error(Exception::new)).when(service).callableMethod();