Jes*_*sse 6 mono spring-mvc spring-test spring-boot mockmvc
抑制单声道并获得身体反应的正确方法是什么?我期望“仅单个项目”出现在 MockHttpServletResponse 的正文响应中。但我看到它是在异步中返回的。
示例方法:
public Mono<String> getData(final String data) {
return this.webClient.get().uri("/dataValue/" + data)
.retrieve()
.bodyToMono(String.class);
}
Run Code Online (Sandbox Code Playgroud)
样本联合体:
@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());
}
Run Code Online (Sandbox Code Playgroud)
测试响应:
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 = []
Run Code Online (Sandbox Code Playgroud)
使用 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());
}
Run Code Online (Sandbox Code Playgroud)
在我看来,您期待的是 StepVerifier。使用它,您可以断言 Mono 和 Flux 数据类型的内容。请参阅https://www.baeldung.com/reactive-streams-step-verifier-test-publisher。
归档时间: |
|
查看次数: |
15269 次 |
最近记录: |