0

I have a REST API developed using Spring Boot and H2 DB which is working fine without any issues.

http://localhost:8080/api/employees

returns

[
   {
      "id":1,
      "name":"Jack"
   },
   {
      "id":2,
      "name":"Jill"
   }
]

Now the problem is that I have two different integration tests for testing this REST API. Both of them are working fine but I am not sure which one should I discard. I understand that both of them are more or less achieving the same result. The first one is using MockMvc while the other one is using TestRestTemplate.

Is there any best practice that I should be following and favoring one over the other?

EmployeeRestControllerIT.java

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestingSampleApplication.class)
@AutoConfigureMockMvc
public class EmployeeRestControllerIT {

    @Autowired
    private MockMvc mvc;

    @Test
    public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception {
        mvc.perform(get("/api/employees")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$[0].name", is("Jack")));
    }

}

EmployeeRestControllerIT2.java

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestingSampleApplication.class)
public class EmployeeRestControllerIT2 {

    @LocalServerPort
    private int port;
    private final TestRestTemplate restTemplate = new TestRestTemplate();
    private final HttpHeaders headers = new HttpHeaders();
    private final String expected = "[{\"id\":1,\"name\":\"Jack\"},{\"id\":2,\"name\":\"Jill\"}]";

    @Test
    public void testRetrieveStudentCourse() throws JSONException {
        String url = "http://localhost:" + port + "/api/employees";
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, GET, entity, String.class);
        JSONAssert.assertEquals(expected, response.getBody(), false);
    }

}
Nital
  • 5,784
  • 26
  • 103
  • 195
  • https://stackoverflow.com/questions/25901985/difference-between-mockmvc-and-resttemplate-in-integration-tests?noredirect=1&lq=1 perfectly answers my question – Nital Nov 29 '17 at 20:45
  • did you find an answer to the question? There are thousands of articles, each is showing just hello world example, as if there is only a single api. What happens i try to test several apis, nothing on that. – Imran May 10 '18 at 18:22
  • @Imran - The answer is in the above comment's link that I have mentioned – Nital May 11 '18 at 20:02

0 Answers0