对业务Service
层的代码进行详尽的单元测试是非常必要的,但也不能忽视Controller
层的测试,毕竟Controller
层的接口输出
都是给前端用的,且Controller
层拿到业务Service
层的返回结果后,通常也会做一些业务处理或者转换的问题,以适配前端的展示需求。
目前参与的项目,都是基于Spring Boot
的,下面就简单介绍一下如何基于Spring Boot 2'
和 Junit 5
进行Controller
层测试。之前已经写过一篇
SpringBoot Controller Post接口单元测试
的文章,这次做一个简单的补充:
Controller
层的get
方法;2.0.4.RELEASE
大版本定了后,就可以像下面这样,引入Spring Boot Test
和 Web
了。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiter-apiartifactId>
<version>5.1.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiter-engineartifactId>
<version>5.1.1version>
<scope>testscope>
dependency>
版本用的是5.1.1
。
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
@RestController
@RequestMapping(value = "hello")
public class HelloController {
@RequestMapping(value = "/create", method = RequestMethod.POST)
String create(@RequestBody(required = false) HelloCreateReq helloCreateReq) {
String msg = helloCreateReq.getMsg();
Integer userId = helloCreateReq.getUserId();
return "msg:"+msg+",userId:"+userId;
}
}
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@DisplayName("测试controller post方法")
void helloCreate() throws Exception {
HelloCreateReq req = new HelloCreateReq();
req.setMsg("test hello create");
req.setUserId(123);
MvcResult mvcResult = mockMvc.
perform(
post("/hello/create")
.contentType(MediaType.APPLICATION_JSON)
.content(JSON.toJSONString(req)))
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
直接执行helloCreate()
方法,就可以调用到Controller
的方法了。由于Spring Boot
下跑单元测试的时候,需要一个Application
,因此我们需要简单的构造一下。
/**
* 由于是基于spring boot test组件进行单元测试,需要构建一个TestApplication上下文
*/
@SpringBootApplication
public class TestApplication {
public static void main(String[] args){
SpringApplicationBuilder builder = new SpringApplicationBuilder();
builder.environment(new StandardEnvironment());
builder.sources(TestApplication.class);
builder.main(TestApplication.class);
builder.run(args);
}
}
如果想调用Controller
层的get
方法,也很简单。
@RestController
@RequestMapping(value = "hello")
public class HelloController {
@RequestMapping(value = "/getMsg", method = RequestMethod.GET)
Integer getMsg(Integer userId) {
return userId;
}
}
对应的test
方法。
@Test
@DisplayName("测试controller get方法")
void getMsg() throws Exception {
MvcResult mvcResult = mockMvc.perform(get("/hello/getMsg?userId=123")).andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
本文只是简单介绍一下基础用法,像mock
技术、验证返回结果、异常处理等手法没有介绍到,留到下次讲Service
层单元测试的时候,再补充。