我使用REST API
和Spring Boot
进行了H2 DB
开发,工作正常,没有任何问题。
http://localhost:8080/api/employees
返回
[
{
"id":1,
"name":"Jack"
},
{
"id":2,
"name":"Jill"
}
]
现在问题是我有两个不同的集成测试来测试这个REST API。它们都工作正常,但我不确定应丢弃哪一个。我知道他们两个或多或少都达到了相同的结果。第一个使用MockMvc
,而另一个使用TestRestTemplate
。
我是否应该遵循并支持其他人的最佳做法?
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);
}
}