Search code examples
spring-bootmodel-view-controllerjunitentityresponse

Testing the controller which returns response entity


I have following the controller which accepts post request and returns Response Entity with body

@RestController
public class UserController {
    @Autowired
    private UserService UserService;
    @RequestMapping(value = "/all", method = POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<ResponseUser>> navigationTree(@RequestBody(required=false) UserDataRequest request) {
        return UserService.sendEntries(request);
    }
}

This is the test I wrote I for it:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    private MockMvc mockMvc;

    @MockBean
    private UserService UserServiceMock;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void returnTopLevel() throws Exception {


        String expectedJson = "[{\"id\":\"11\",\"name\":\"11\"},{\"id\":\"22\",\"name\":\"22\"}]";
        MvcResult result = this.mockMvc.perform(post("/all")
                 .contentType(MediaType.APPLICATION_JSON)
                 .content("")
                 .accept(MediaType.APPLICATION_JSON))
                 .andExpect(status().isOk()).andReturn();

        String actualJson = result.getResponse().getContentAsString();

       // System.out.println(result);

        //assertThat(Objects.equals(expectedJson, actualJson)).isTrue();

         verify(UserServiceMock,times(1)).sendEntries(null);

    }
}

I want to compare string received in response body to expected string.

  1. I tried the string comparison but it's not working

Errors :

    assertThat(Objects.equals(expectedJson, actualJson)).isTrue();

and actualjson is empty.

What are the other ways?


Solution

  • You need to mock the UserService to return something before executing this.mockMvc.perform. Something like this:

    when(UserServiceMock.sendEntries(null)).thenReturn(expectedResponceEntity);
    

    So just construct the expected response then mock UserService to return it.