持有TTD(测试驱动开发)理念的开发人员认为,单元测试在编程过程中扮演了举足轻重的地位,虽然看起来花费了编码时间,但却能够极大的减少调试时间,是非常重要的开发过程。
以Web为例,在Core页面中勾选Web即可。下一步,直到构造项目完成即可。很简单,不再赘述
pom文件内容如下:
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.3.RELEASEversion>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>demoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>demoname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
注意:由于勾选了核心模块web,因此pom文件会自动导入spring-boot-starter-web和spring-boot-starter-test,代码只需要导入alibaba的jar包fastjson即可。
在项目中添加类型TestUnit,并为该类型中添加两个简单的Http请求,一个Get请求,一个Post请求。
项目结构如下:
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请求。
这也比较简单,不再赘述。
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]
}
在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
单元测试用例很重要,在步入高级程序员的过程中,必不可少。
《重构 改善既有代码的设计》之JUnit测试框架以及IDEA与JUnit整合