How to junit test a method with Mono return type

Viewed 4222

What is the proper way to junit mono and get a body response? I expected "Single Item Only" to be in the body response of MockHttpServletResponse. But instead I see it's returned in Async.

Sample Method:

public Mono<String> getData(final String data) {
    return this.webClient.get().uri("/dataValue/" + data)
        .retrieve()
        .bodyToMono(String.class);
}

Sample 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);

this.mockMvc.perform(get("/some/rest/toget/data")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status()
        .isOk());
}

Test Response:

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 = []

Updated Junit with StepVerifier:

@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 Answers
Related