我的控制器的模擬回傳回應有問題。
異步回應作為實際 POJO 而不是序列化 json 回傳。
運行應用程式并使用 Postman,回傳的回應確實是一個 JSON 物件……但測驗它回傳我創建的實際模擬 POJO……這是我的測驗用例。
@WebMvcTest(CustomerController.class)
class CustomerControllerTest {
@Autowired
MockMvc mvc;
@MockBean
private CustomerService customerService;
private Mono<OtcBalanceResponse> responseMono;
private OtcBalanceResponse otcResponseMock;
@BeforeEach
void setupMocks() {
OtcBalanceResponse otcResponseMock = new OtcBalanceResponse();
otcResponseMock.setOtcBalance(new BigDecimal("1.30"));
otcResponseMock.setUserId("testID");
responseMono = Mono.just(otcResponseMock);
}
@Test
void testGetCustomerOTCBalance() throws Exception {
when(customerService.getCustomerOTCBalance((OtcBalanceRequest) any()))
.thenReturn(responseMono);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/customer/otc-balance").accept(MediaType.APPLICATION_JSON);
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.otcBalance").value(1.30));
}
}
這是我的控制器類
@GetMapping("/otc-balance")
public Mono<OtcBalanceResponse> getCustomerOTCBalance(OtcBalanceRequest otcBalanceRequest){
return customerService.getCustomerOTCBalance(otcBalanceRequest);
}
這是我的服務
public Mono<OtcBalanceResponse> getCustomerOTCBalance(OtcBalanceRequest request) {
return webClientBuilder
.baseUrl(customerBase)
.build()
.post()
.uri(otcBalancePath)
.body(BodyInserters.fromValue(request))
.retrieve()
.bodyToMono(OtcBalanceResponse.class);
}
這是我記錄的結果
Async:
Async started = true
Async result = OtcBalanceResponse(otcBalance=1.30, otcRolloverFlag=false, isIncommMember=false, otcStartDate=null, otcEndDate=null)
uj5u.com熱心網友回復:
當您使用異步編碼(而不是完整的 webflux)時,您也需要這樣做MockMvc。的javadoc有MockMvcRequestBuilders一個這樣的例子。將其應用于您的代碼將使其成為這樣。
@Test
void testGetCustomerOTCBalance() throws Exception {
when(customerService.getCustomerOTCBalance((OtcBalanceRequest) any()))
.thenReturn(responseMono);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/customer/otc-balance").accept(MediaType.APPLICATION_JSON);
MvcResult result = mvc.perform(requestBuilder).andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(result))
.andExpect(MockMvcResultMatchers.jsonPath("$.otcBalance").value(1.30));
}
類似的東西。
uj5u.com熱心網友回復:
您似乎正在使用 webflux,最簡單的方法是使用特定于 webflux 的類:
- WebFluxTest 而不是 WebMvcTest
- WebTestClient 而不是 MockMvc
@WebFluxTest(CustomerController.class)
class CustomerControllerTest {
@Autowired
private WebTestClient webClient;
// ...
@Test
void testGetCustomerOTCBalance() throws Exception {
when(customerService.getCustomerOTCBalance(any()))
.thenReturn(responseMono);
webClient.get().uri("/customer/otc-balance")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.otcBalance").isEqualTo(1.30);
}
}
其他評論 - 你不是OtcBalanceRequest控制器 - 但any()引數匹配器接受 null。使用eq引數匹配器將使您的測驗更好 - 您將檢查請求是否被控制器正確反序列化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530881.html
