MOcking a COntroller handler method

Viewed 41

Very fresher . Learning Junit. I have this method and I need to write the JUnit for that method. When I tried to write its returning null. Can anyone of you help me on this. #Method

 @PutMapping(value = {"/**"})
public ResponseEntity<String> putRequest(@RequestBody final String payload, final 
         HttpServletRequest request) {
        return Proservice.put(request, payload);

}

@Test
void testPutRequest() throws Exception {
    // Setup
    when(ProService.put(any(HttpServletRequest.class), eq("payload"))).thenReturn(new 
  ResponseEntity<>("body", HttpStatus.OK));

    // Run the test
    final MockHttpServletResponse response = mockMvc.perform(put("/**")
            .content("content").contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andReturn().getResponse();

    // Verify the results
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(response.getContentAsString()).isEqualTo("expectedResponse");
}
1 Answers

There are multiple ways to test a spring controller. Depends on whether you want to test the controller class or test a application context . https://reflectoring.io/spring-boot-test/ will provide you detailed guide on how to go about testing

Related