tonglin0325的个人主页

SpringBoot学习笔记——mock

可以使用mock对springboot web接口进行测试

1.依赖

1
2
3
4
5
6
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

2.编写测试用例

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
import org.apache.tomcat.util.codec.binary.Base64;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import javax.annotation.Resource;

import java.nio.charset.StandardCharsets;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

@Resource
private MockMvc mockMvc;

@Test
public void helloTest() throws Exception {
String expect = "{\"code\":200,\"msg\":\"hello: 1\",\"data\": null}";
String auth = "admin:admin";
byte[] originAuth = auth.getBytes(StandardCharsets.US_ASCII);
byte[] encodedAuth = Base64.encodeBase64(originAuth);
String authHeader = "Basic " + new String(encodedAuth);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", authHeader);
mockMvc.perform(MockMvcRequestBuilders.get("/hello/1")
.headers(headers))
.andExpect(MockMvcResultMatchers.content().json(expect))
.andDo(MockMvcResultHandlers.print());
}

}

测试GET请求

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
MockHttpServletRequest:
HTTP Method = GET
Request URI = /hello/1
Parameters = {}
Headers = [Authorization:"Basic YWRtaW46YWRtaW4="]
Body = null
Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=admin, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=1], Granted Authorities=[ROLE_USER]]]}

Handler:
Type = com.example.demo.controller.HelloController
Method = com.example.demo.controller.HelloController#hello(Integer)

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"code":200,"msg":"hello: 1","data":null}
Forwarded URL = null
Redirected URL = null
Cookies = []

Process finished with exit code 0

测试POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
@Transactional
public void createUserTest() throws Exception {
String expect = "{\"code\":200,\"msg\":\"success\",\"data\": null}";
String auth = "admin:admin";
byte[] originAuth = auth.getBytes(StandardCharsets.US_ASCII);
byte[] encodedAuth = Base64.encodeBase64(originAuth);
String authHeader = "Basic " + new String(encodedAuth);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", authHeader);
mockMvc.perform(
MockMvcRequestBuilders.post("/user")
.headers(headers)
.contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"username\": \"admin\",\n" +
" \"password\": \"admin\"\n" +
"}"))
.andExpect(MockMvcResultMatchers.content().json(expect))
.andDo(MockMvcResultHandlers.print());
}  

在对POST请求的测试中,添加了
 @Transactional 注解,用于在对测试中插入的数据进行回滚,避免插入脏数据

使用 @SpringBootTest注解 如何配置测试环境请参考:Spring Boot 2 实战:mock测试你的web应用