Test工具类

First Post:

Last Update:

Word Count:
1k

Read Time:
6 min

BasicMockRequest

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
public interface BasicMockRequest {

/**
* 发送get请求
*
* @param uri
* @return
*/
default RequestBuilder get(String uri) {
return MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_UTF8);
}

/**
* 发送get请求并携带token
*
* @param uri
* @param token
* @return
*/
default RequestBuilder getAndTakeToken(String uri, String token) {
return MockMvcRequestBuilders.get(uri)
.header("token", token)
.accept(MediaType.APPLICATION_JSON_UTF8);
}

/**
* 发送post请求
*
* @param uri
* @return
*/
default RequestBuilder post(String uri) {
return MockMvcRequestBuilders.post(uri)
.accept(MediaType.APPLICATION_JSON_UTF8);
}

/**
* 发送post请求并携带token和请求体
*
* @param uri
* @param token
* @param data
* @return
*/
default RequestBuilder postAndTakeTokenAndData(String uri, String token, Object data) {
String content = Optional.ofNullable(data)
.map(JsonUtils::quietlySerialize)
.orElse("");
return MockMvcRequestBuilders.post(uri)
.header("token", token)
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content);
}

/**
* 发送post请求并携带请求参数
*
* @param uri
* @param data
* @return
*/
default RequestBuilder postAndTakeRequestParameter(String uri, Object data) {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(uri)
.accept(MediaType.APPLICATION_JSON_UTF8);

Map<String, String> parameterMap = ObjectAttribute.toParameterMap(data);

parameterMap.forEach((k, v) -> requestBuilder.param(k, v));

return requestBuilder;
}

/**
* 发送post请求并携带token和请求参数
*
* @param uri
* @param token
* @param data
* @return
*/
default RequestBuilder postAndTokenAndRequestParameter(String uri, String token, Object data) {
return ((MockHttpServletRequestBuilder) postAndTakeRequestParameter(uri, data))
.header("token", token);
}

/**
* 发送post请求并携带请求体
*
* @param uri
* @param data
* @return
*/
default RequestBuilder postAndTakeRequestBody(String uri, Object data) {
return MockMvcRequestBuilders.post(uri)
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JsonUtils.quietlySerialize(data));
}
}

MockContext

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
public interface MockContext {

/**
* 获取测试用户
*
* @return
*/
User getMockUser();

/**
* 获取测试token
*
* @return
*/
String getMockToken();

/**
* 获取测试url
*
* @return
*/
String getBaseUrl();

/**
* 获取测试的mvc环境
*
* @return
*/
MockMvc getMockMvc();
}

MockContextImpl

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@Component
@DependsOn("tokenUtils")
@ConditionalOnProperty(value = "enroll.mock", havingValue = "true")
public class MockContextImpl implements MockContext {

private static final Logger log = LoggerFactory.getLogger(MockContextImpl.class);

/**
* 测试用的token(有效期:永久)
*/
private String mockToken;

private User mockUser;

private MockMvc mockMvc;

@Value("${server.port}")
private String port;

private String baseUrl = "http://localhost:%s/api";

@Autowired
private UserDao userDao;

@Autowired
private TokenDao tokenDao;

@Autowired
private ProcessService processService;

@Autowired
private ProcessDao processDao;

@Autowired
private WebApplicationContext webApplicationContext;

@Override
public User getMockUser() {
return mockUser;
}

@Override
public String getMockToken() {
return mockToken;
}

@Override
public String getBaseUrl() {
return baseUrl;
}

@Override
public MockMvc getMockMvc() {
return mockMvc;
}

@PostConstruct
public void initialization() {
mockUser = createMockUserAndInsertToDatabase();
mockToken = createMockTokenAndInsertToDatabase();
baseUrl = String.format(baseUrl, port);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.alwaysDo(MockMvcResultHandlers.print())
.build();

log.info("initialization mock user: {} success", mockUser.getId());
log.info("initialization mock token: {} success", mockToken);
log.info("initialization baseUrl: {} success", baseUrl);
log.info("initialization mock web environment success");
}

private String createMockTokenAndInsertToDatabase() {
// 世界人均寿命: 71岁 --- 2021/09/23
final long year = 365L;
long hundredYearLater = System.currentTimeMillis() + Duration.ofDays(year * 100L).toMillis();
Date permanent = new Date(hundredYearLater);

log.info("hundredYearLater: {}", DateUtil.format(permanent, "yyyy/MM/dd HH:mm:ss"));
Token token = TokenUtils.createTokenAndSpecifyExpirationTime(mockUser.getId(), permanent);

tokenDao.insertSelective(token);

return token.getToken();
}

private User createMockUserAndInsertToDatabase() {

Date createTime = new Date();
String randomOpenId = UUID.randomUUID().toString().replaceAll("-", "");

User user = new User();
user.setOpenId(randomOpenId);
user.setStatus(UserStatusEnum.REGISTERED.getStatus());
user.setAuthority(AuthorityEnum.PROGRAMMING_DEPARTMENT_ADMINISTRATOR.getAuthority());
user.setTerm(SystemConstant.TERM);
user.setCreateTime(createTime);
user.setUpdateTime(createTime);

userDao.insertSelective(user);

processService.initialUserProcess(user.getId());

return user;
}

/**
* 删除测试用户和测试token
*/
@PreDestroy
public void destroy() {
deleteMockUserIfExists();
deleteMockTokenIfExists();
}

private void deleteMockUserIfExists() {
Optional.ofNullable(mockUser)
.ifPresent(user -> {
userDao.deleteByPrimaryKey(user.getId());
processDao.deleteByUserId(user.getId());
log.info("删除mock user: {} 成功", user.getId());
});
}

private void deleteMockTokenIfExists() {
Optional.ofNullable(mockToken)
.ifPresent(token -> {
tokenDao.deleteByToken(token);
log.info("删除mock token: {} 成功", token);
});
}
}

ObjectAttribute

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class ObjectAttribute {

private static final int getStringLength = 3;

private String attributeName;

private Object attributeValue;

public ObjectAttribute(Object target, Method method) {
String unmodifiedAttributeName = method.getName().substring(getStringLength);
if (unmodifiedAttributeName.isEmpty()) {
throw new IllegalArgumentException("getter方法名称错误: " + method.getName());
}
// 首字母转小写
attributeName = Character.toLowerCase(unmodifiedAttributeName.charAt(0)) + unmodifiedAttributeName.substring(1);
try {
attributeValue = method.invoke(target);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("getter方法必须为无参方法", e);
}
}

public String getAttributeName() {
return attributeName;
}

public Object getAttributeValue() {
return attributeValue;
}

public static Map<String, String> toParameterMap(Object data) {
if (data == null) {
return Collections.emptyMap();
}
Map<String, String> objectAttributeMap = Arrays.stream(data.getClass().getDeclaredMethods())
.filter(method -> method.getName().startsWith("get"))
.map(method -> new ObjectAttribute(data, method))
.collect(Collectors.toMap(ObjectAttribute::getAttributeName, ObjectAttribute::toRequestParam));

return objectAttributeMap;
}

public String toRequestParam() {
return javaDataToRequestQueryParam(attributeValue);
}

private static String javaDataToRequestQueryParam(Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof List) {
return JsonUtils.quietlySerialize(value);
} else if (value instanceof Map) {
return JsonUtils.quietlySerialize(value);
} else if (value.getClass().isArray()) {
return JsonUtils.quietlySerialize(value);
} else if (value instanceof Date) {
return DateUtil.format((Date) value, "yyyy/MM/dd HH:mm:ss");
}
throw new RuntimeException("无法识别的类型: " + value.getClass().getName());
}
}

PrintPrettyJsonResultHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class PrintPrettyJsonResultHandler implements ResultHandler {

private static final Logger log = LoggerFactory.getLogger(PrintPrettyJsonResultHandler.class);

@Override
public void handle(MvcResult mvcResult) throws Exception {
MockHttpServletResponse response = mvcResult.getResponse();
response.setCharacterEncoding("UTF-8");
String content = response.getContentAsString();
String prettyString = JsonUtils.toPrettyString(content);
log.info("\n{}\n", prettyString);
}
}