spirng boot 测试

-


@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Autowired
private UserController userController;

@Autowired
private ObjectMapper om;

@Test
public void contextLoads() throws Exception {
assertThat(userController).isNotNull();
}

@Test
public void hello() throws JsonMappingException, JsonProcessingException {
String resStr = this.restTemplate.getForObject("http://localhost:" + port + "/v1/users/hello", String.class);
JsonNode resJson = om.readTree(resStr);

assertThat(resJson.get("data").asText()).isEqualTo("hello world");
}

}

@SpringBootTest @AutoConfigureMockMvc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerMockTest {

@Autowired
private ObjectMapper om;

@Autowired
private MockMvc mockMvc;

@Test
public void shouldReturnDefaultMessage() throws Exception {
String resStr = this.mockMvc//
.perform(get("/v1/users/hello")//
.contentType(MediaType.APPLICATION_JSON))//
.andDo(print())//
.andExpect(status().isOk())//
.andReturn()//
.getResponse()//
.getContentAsString();

JsonNode resJson = om.readTree(resStr);

assertThat(resJson.get("data").asText()).isEqualTo("hello world");
}

}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×