为REST API编写Spring Boot Integration Test的正确方法是什么

时间:2017-11-29 20:02:20

标签: java rest spring-boot integration-testing spring-boot-test

我使用REST APISpring 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);
    }

}

0 个答案:

没有答案