我有一個使用 Spring Webflux 和 reactor 的服務層,我正在為此撰寫單元測驗。我能夠測驗良好的回應場景,但不確定如何onErrorResume()使用 StepVerifier進行測驗。另外請讓我知道是否有更好的方法來處理我的控制器中的例外(例如:使用switchIfEmpty())
這是我的控制器方法
public Mono<SomeType> getInfo(Integer id) {
return webClient
.get()
.uri(uriBuilder -> uriBuilder.path())
.header("", "")
.header("", "")
.header("", "")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.retrieve()
.bodyToMono(POJO.class)
.onErrorResume(ex -> {
if (ex instanceof WebFaultException)
return Mono.error(ex);
return Mono.error(new WebFaultException(ex.getMessage(), "Error on API Call", HttpStatus.INTERNAL_SERVER_ERROR));
});
}
}
uj5u.com熱心網友回復:
您可以模擬 webclient 并在呼叫 webclientMock.get() 時使用Mockito.doThrow。
YourWebClient webclientMock = mock(YourWebClient.class);
doThrow(RuntimeException.class)
.when(webclientMock)
.get();
// Call your method here
Exception exception = assertThrows(RuntimeException.class, () -> {
YourController.getInfo(someIntValue);
});
// If you chose to raise WebFaultException, addittionaly assert that the return values ( message, status) are the one you expected
uj5u.com熱心網友回復:
WebClient無需模擬WebClient類本身即可測驗您的代碼的另一種方法,因為這可能很快變得非常混亂,是WebClient使用ExchangeFunction回傳您期望的任何回應或錯誤的來構建您的代碼。我發現這是模擬單元測驗WebClient和啟動Wiremock單元測驗之間的一種愉快的媒介。
@Test
void ourTest() {
ExchangeFunction exchangeFunction = mock(ExchangeFunction.class);
// this can be altered to return either happy or unhappy responses
given(exchangeFunction.exchange(any(ClientRequest.class))).willReturn(Mono.error(new RuntimeException()));
WebClient webClient = WebClient.builder()
.exchangeFunction(exchangeFunction)
.build();
// code under test - this should live in your service
Mono<String> mono = webClient.get()
.uri("http://someUrl.com")
.retrieve()
.bodyToMono(POJO.class)
.onErrorResume(ex -> {
if (ex instanceof WebFaultException)
return Mono.error(ex);
return Mono.error(new WebFaultException(ex.getMessage(), "Error on API Call", HttpStatus.INTERNAL_SERVER_ERROR));
});
StepVerifier.create(mono)
.expectError(RuntimeException.class)
.verify();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370994.html
標籤:爪哇 单元测试 莫基托 弹簧-webflux 项目反应堆
下一篇:在R中的各種資料幀之間回圈
