1简介
持有TTD(测试驱动开发)理念的开发人员认为,单元测试在编程过程中扮演了举足轻重的地位,虽然看起来花费了编码时间,但却能够极大的减少调试时间,是非常重要的开发过程。
2对Spring Boot程序进行单元测试
2.1使用Spring Initializer构造web程序
以Web为例,在Core页面中勾选Web即可。下一步,直到构造项目完成即可。很简单,不再赘述
2.2在pom文件中引入fastjson包
pom文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--仅需手动导入fastjson包即可,spring-boot-starter-test自动导入-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
注意:由于勾选了核心模块web,因此pom文件会自动导入spring-boot-starter-web和spring-boot-starter-test,代码只需要导入alibaba的jar包fastjson即可。
2.3项目结构
在项目中添加类型TestUnit,并为该类型中添加两个简单的Http请求,一个Get请求,一个Post请求。
项目结构如下:
2.3.1 TestUnit内容
package com.example.demo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 单元测试控制类
*
* @Owner:
* @Time: 2019/3/12-22:35
*/
@RestController
public class TestUnit {
@RequestMapping("/")
public String hello() {
return "hello";
}
@PostMapping(value = "/page", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getPageList(@RequestBody JSONObject pageObj) {
int pageNo = pageObj.getIntValue("pageNo");
int pageSize = pageObj.getIntValue("pageSize");
//handle pageObj
JSONArray list = new JSONArray();
list.fluentAdd(5).fluentAdd(6);
JSONObject result = JSONObject.parseObject(pageObj.toJSONString());
result.put("list", list);
return result.toJSONString();
}
}
在上述Controller类中,添加了两个函数,一个名为hello的get请求,一个为需要传入JSON对象的getPageList请求。
这也比较简单,不再赘述。
2.3.2通过IDEA自带的Test Restful Web Service测试代码
IDEA自带一个良好的工具Test Restful Web Service,位置在
Tools -> HTTP Client -> TestRestful Web Service
由于get请求没有参数,很简单,测试部再赘述,主要测试Post请求,
如果在其中不指定Content-Type的header,
则服务弹出如下的结果:
可以看出结果status为415,Unsupported Media Type,
{
"timestamp": "2019-03-12T15:45:54.808+0000",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type '*/*;charset=UTF-8' not supported",
"path": "/page"
}
因此,如果在Controller接口中指定了@RequestBody JSONObject,则一定要指定Content-Type
若指定了Content-Type为application/json,则接口会成功执行,弹出如下的结果:
可以看到响应中已经有了结果
{
"pageNo": 1,
"pageSize": 10,
"list": [5, 6]
}
2.4TestUnitTest类,编写测试代码
2.4.1 测试代码
在IDEA集成了JUnit测试的基础在类TestUnit上点击
Ctrl + Alt + T
即可自动生成测试框架。
该类的内容如下:
package com.example.demo;
import com.alibaba.fastjson.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@AutoConfigureMockMvc
public class TestUnitTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
JSONObject page = null;
@Before
public void setUp() throws Exception {
page = new JSONObject();
page.fluentPut("pageNo", 1);
page.fluentPut("pageSize", 10);
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void hello() throws Exception{
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/"))
.andReturn();
int status = result.getResponse().getStatus();
String contentType = result.getResponse().getContentType();
String url = result.getRequest().getRequestURI();
String content = result.getResponse().getContentAsString();
int contentLength = result.getResponse().getContentLength();
assertEquals(HttpStatus.OK.value(), 200);
assertEquals("hello", content);
}
@Test
public void getPageList() throws Exception {
MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/page")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(page.toJSONString()))
.andReturn();
int status = result.getResponse().getStatus();
String contentType = result.getResponse().getContentType();
String url = result.getRequest().getRequestURI();
String content = result.getResponse().getContentAsString();
int contentLength = result.getResponse().getContentLength();
assertEquals(HttpStatus.OK.value(), 200);
assertEquals("/page", url);
assertEquals(MediaType.APPLICATION_JSON_UTF8_VALUE,contentType);
JSONObject res = JSONObject.parseObject(content);
assertEquals(2,res.getJSONArray("list").size());
}
}
注意, 必须在@SpringBootTest注解中指定(classes = DemoApplication.class)
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test
2.4.2 代码分析
2.4.3 测试结果
可以看到两个测试用例均通过了测试。
3总结
单元测试用例很重要,在步入高级程序员的过程中,必不可少。