前言

最近有小伙伴问到怎么给 controller的接口写单元测试。

 

单元测试是开发必不可少的一个环节。

既然有人问到了,那我觉得可能不止一个人不会,那就按照惯例,出手。

 

正文

内容:

主要是get 和 post 两种请求方式的接口 的 单元测试写法。

get方式请求   介绍 3种传参:

①@PathVariable ②@RequestParam("id") ③类传参 如 User user

post方式请求  介绍 1种传参: @RequestBody

@RequestHeader请求头参数添加参数

上代码 :

先看GET方式请求,简单写三个示例接口

@GetMapping("/getId/{id}")

public String pathVariableTest(@PathVariable Integer id) {

return "id: "+id;

}

@GetMapping("/getId")

public String requestParamTest( @RequestParam("id") Integer id) {

return "id: "+id;

}

@GetMapping("/getUser")

public String requestParamObjectTest( User user) {

return user.toString();

}

然后我们来针对这三个get请求接口写单元测试

pom.xml 加入测试使用的jar依赖

junit

junit

test

org.springframework.boot

spring-boot-starter-test

test

创建一个单元测试类 MyControllerTest.java

 代码:

import org.junit.runner.RunWith;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringRunner.class)

@SpringBootTest

@WebAppConfiguration

public class MyControllerTest {

protected Logger logger = LoggerFactory.getLogger(MyControllerTest.class);

}

 写下来开始写 针对controller 的 单元测试代码:

 代码:

@Autowired

DoTestController doTestController;

private MockMvc mockMvc;

@Before

public void setup() {

mockMvc = MockMvcBuilders.standaloneSetup(doTestController).build();

}

 

首先针对这种场景的GET请求,传入参数的,我们怎么写单测? @RequestParam("id")

 代码: 

@Test

public void getTest() throws Exception {

MvcResult mvcResult = mockMvc.perform(

MockMvcRequestBuilders.get("/getId")

.param("id", "123")

)

.andExpect(MockMvcResultMatchers.status().isOk())

.andDo(MockMvcResultHandlers.print())

.andReturn();

logger.info("调用返回的结果:{}", mvcResult.getResponse().getContentAsString());

}

ps: 多个  @RequestParam  就同样 一直 .param即可

示例:

 当然也可以通过map传值,传多个:

 

 跑一下单测看看效果:

 

然后是@PathVariable 传参方式:

 单测写法:

 代码:

@Test

public void pathVariableTest() throws Exception {

Integer id = 888;

MvcResult mvcResult = mockMvc.perform(

MockMvcRequestBuilders.get("/getId/" + id)

)

.andExpect(MockMvcResultMatchers.status().isOk())

.andDo(MockMvcResultHandlers.print())

.andReturn();

logger.info("调用返回的结果:{}", mvcResult.getResponse().getContentAsString());

}

 

然后是传类的情景:

  单测写法:

代码:  

@Test

public void getTestObject() throws Exception {

MvcResult mvcResult = mockMvc.perform(

MockMvcRequestBuilders.get("/getUser")

.param("userId", "123")

.param("name", "JCccc")

.param("age", "18")

.param("userCode", "100244")

.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)

)

.andExpect(MockMvcResultMatchers.status().isOk())

.andDo(MockMvcResultHandlers.print())

.andReturn();

logger.info("调用返回的结果:{}", mvcResult.getResponse().getContentAsString());

}

然后看下POST 请求方式的接口 单测写法

 

顺便把请求头参数方式一并写了:

 代码:  

@Test

public void postTest() throws Exception {

User user = new User();

user.setUserId(100011L);

user.setName("JCccc");

user.setUserCode("100244");

user.setAge(18);

String strJson = JSON.toJSONString(user);

MvcResult mvcResult = mockMvc.perform(

MockMvcRequestBuilders.post("/getRequestBodyValue")

.header("token", "收藏点赞")

.accept(MediaType.parseMediaType("application/json;charset=UTF-8"))

.contentType(MediaType.APPLICATION_JSON)

.content(strJson)

)

.andExpect(MockMvcResultMatchers.status().isOk())

.andDo(MockMvcResultHandlers.print())

.andReturn();

logger.info("调用返回的结果:{}", mvcResult.getResponse().getContentAsString());

}

效果:

 

文章来源

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。