复杂系统开发中, 单元测试是必不可少的一个环节。而对于接口的测试,小型系统一般使用PostMan等工具对接口进行简单测试,但它有重复操作性差,返回值确认困难等缺点。SpringBoot提供了TestRestTemplate来针对接口编写单元测试。
pom.xml引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
看一个基础的测试用例:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MinimallTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
private String xAuthToken = "";
private HttpHeaders headers = new HttpHeaders();
@Before
public void setHeaders() {
JSONObject result = exchangeForJSON(HttpMethod.POST, "/wx/login", null);
assertThat(result.getJSONObject("data").getString("sessionId")).isNotEmpty();
xAuthToken = result.getJSONObject("data").getString("sessionId");
headers.add("X-Requested-With", "XMLHttpRequest");
headers.add("X-Auth-Token", xAuthToken);
}
@After
public void clearHeaders(){
headers.clear();
}
/**
* 首页数据
*/
@Test
public void homepage() {
JSONObject result = exchangeForJSON(HttpMethod.GET, "/wx/homepage", null);
assertThat(result.getJSONObject("data").getString("banners")).isNotNull();
assertThat(result.getJSONObject("data").getString("recommends")).isNotNull();
assertThat(result.getJSONObject("data").getString("categories")).isNotNull();
}
private JSONObject exchangeForJSON(HttpMethod method, String url, MultiValueMap<String, String> formData, String... variables) {
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);
if(method.equals(HttpMethod.POST)){
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
}
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:" + port + "/minimall_api/" + url,
method, entity, String.class, variables);
JSONObject result = JSON.parseObject(response.getBody());
log.info(result.toJSONString());
return result;
}
类上的两个注解,@RunWith(SpringRunner.class)为测试用例添加Spring支持,而@SpringBootTest注解让每次测试运行时都会启动一个随机端口。只要在port属性上添加@LocalServerPort就可以获取到这个随机的端口用来访问。同时,使用了@SpringBootTest之后,我们就可以使用@Autowired来注入一个TestRestTemplate用来模拟Http请求。
@Before和@After顾名思义,会在每个测试之前和之后分别执行。
那么要发送一个GET请求的话,我们可以直接使用
restTemplate.getForEntity()
也可以使用通用的
restTemplate.exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... urlVariables)
比如:
restTemplate.exchange( "http://localhost:" + port + "/minimall_api/login?userId={1}&password={2}", HttpMethod.GET, new HttpEntity<>(), String.class, "abc", "123456")
要发送POST请求就相对复杂一点, 要根据接口的需求设置Content-Type。比如,要发送一个multipart/formdata的请求:
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("userId", "abc");
formData.add("password", "123456");
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);
restTemplate.exchange("http://localhost:" + port + "/minimall_api/" + url, HttpMethod.POST, entity, String.class);
这里要注意的是HttpEntity的body一定要是MultiValueMap的, 这样在测试运行的时候, RestTemplate才会判断这个消息应当调用FormHttpMessageConverter来进行转换, 判断逻辑是在RestTemplate的doWithRequest里:
public void doWithRequest(ClientHttpRequest httpRequest) throws IOException {
...
for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<Object> genericConverter =
(GenericHttpMessageConverter<Object>) messageConverter;
if (genericConverter.canWrite(requestBodyType, requestBodyClass, requestContentType)) {
if (!requestHeaders.isEmpty()) {
requestHeaders.forEach((key, values) -> httpHeaders.put(key, new LinkedList<>(values)));
}
logBody(requestBody, requestContentType, genericConverter);
genericConverter.write(requestBody, requestBodyType, requestContentType, httpRequest);
return;
}
}
else if (messageConverter.canWrite(requestBodyClass, requestContentType)) {
if (!requestHeaders.isEmpty()) {
requestHeaders.forEach((key, values) -> httpHeaders.put(key, new LinkedList<>(values)));
}
logBody(requestBody, requestContentType, messageConverter);
((HttpMessageConverter<Object>) messageConverter).write(
requestBody, requestContentType, httpRequest);
return;
}
...
}
这里遍历注册的messagerConverter, 先判断canWrite()是否为true, 是的话就调用messageConverter.write()进行写。
那么看一下FormHttpMessageConvertert的canWrite():
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
if (!MultiValueMap.class.isAssignableFrom(clazz)) {
return false;
}
if (mediaType == null || MediaType.ALL.equals(mediaType)) {
return true;
}
for (MediaType supportedMediaType : getSupportedMediaTypes()) {
if (supportedMediaType.isCompatibleWith(mediaType)) {
return true;
}
}
return false;
}
可以看到只有requestBodyClass是MultiValueMap及它的子类时, 才会返回true。
而FormHttpMessageConverter的主要作用就是将Map转换成请求体,并在参数间自动添加boundary, 再把boundary设置到Content-Type里。 没有经过这一步的话,服务器会因为缺少boundary头而无法解析这个multipart/formdata。
看一下FormHttpMessageConverter.write():
private void writeMultipart(final MultiValueMap<String, Object> parts,
HttpOutputMessage outputMessage) throws IOException {
final byte[] boundary = generateMultipartBoundary();
Map<String, String> parameters = new LinkedHashMap<>(2);
if (!isFilenameCharsetSet()) {
parameters.put("charset", this.charset.name());
}
parameters.put("boundary", new String(boundary, "US-ASCII"));
MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
HttpHeaders headers = outputMessage.getHeaders();
headers.setContentType(contentType);
if (outputMessage instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
streamingOutputMessage.setBody(outputStream -> {
writeParts(outputStream, parts, boundary);
writeEnd(outputStream, boundary);
});
}
...
}
可以看到自动帮我们生成了boundary,并且用这个boundary去分离参数。
那么同样的, 要发送application/json的请求, 我们就要用JSONObject作为HttpEntity的body。
对于返回的结果,org.assertj.core.api.Assertions.assertThat()提供了更方便的assertion便于我们确认。比如:
//确认返回的banners不为空
assertThat(result.getJSONObject("data").getString("banners")).isNotEmpty();
//确认返回的集合里存在且仅存在一条productSkuId和productQuantity符合条件的条目
assertThat(orderItemResult.getJSONArray("data")).haveExactly(1, new Condition<>(s->{
JSONObject j = (JSONObject) s;
if(j.getString("productSkuId").equals("565250428514734082") && j.getIntValue("productQuantity") == 1){
return true;
}
return false;
}, "s"));
其原理是根据传入assertThat()的变量类型, 调用不同的构造器, 返回不同的AbstractAssert的实现, 常用的有基于数值、String、List等类型的判断。
编写覆盖完整的单元测试, 有助于我们在调整接口后,快速确认所有原有功能仍旧正常运转。