使用junit mono并获得主体响应的正确方法是什么?我希望“Single Item Only”出现在MockHttpServletResponse的主体响应中,但我看到它以异步方式返回。
取样方法:
public Mono<String> getData(final String data) {
return this.webClient.get().uri("/dataValue/" + data)
.retrieve()
.bodyToMono(String.class);
}
示例J单位:
@WebMvcTest(DataController.class)
public class DataMockTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private Service service;
@Test
public void getDataTest() throws Exception {
Mono<String> strMono = Mono.just("Single Item Only");
when(service.getData("DATA")).thenReturn(strMono);
this.mockMvc.perform(get("/some/rest/toget/data")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status()
.isOk());
}
测试响应:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /some/rest/toget/data
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
Body = null
Session Attrs = {}
Async:
Async started = true
Async result = Single Item Only
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
使用StepVerifier更新了Junit:
@WebMvcTest(DataController.class)
public class DataMockTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private Service service;
@Test
public void getDataTest() throws Exception {
Mono<String> strMono = Mono.just("Single Item Only");
when(service.getData("DATA")).thenReturn(strMono);
//Added this which verifies the mono method. How to mock it so the API would return the mono value?
StepVerifier.create(service.getDATA("DATA"))
.assertNext(data -> {
assertNotNull(data);
assertEquals("Single Item Only", data);
}).verifyComplete();
this.mockMvc.perform(get("/some/rest/toget/data")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status()
.isOk());
}
1条答案
按热度按时间ma8fv8wu1#
在我看来,您期待的是StepVerifier,使用它可以AssertMono和Flux数据类型的内容,请参考https://www.baeldung.com/reactive-streams-step-verifier-test-publisher。