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