controller单元测试
AutoConfigureMockMvc
以上是针对业务层测试,如果想进行接口API测试怎么办呢,难道,开发完成每次调用postman一个个测吗?答案当然是no
,不过,你也可以选择一个个测试没什么问题,如果你想通过代码实现模拟http请求就要用到我们的@AutoConfigureMockMvc
注解,使用了MockMvc无需启动项目,就可实现接口测试。
以下用到的MockMvc方法介绍
mockMvc.perform
:执行请求MockMvcRequestBuilders.get
:还支持post、put、delete等contentType(MediaType.APPLICATION_JSON_UTF8)
:表示请求传输的Conent-Type=application/json;charset=utf-8
- accept(MediaType.APPLICATION_JSON)):客户端希望接收的
Conent-Type=application/json;
andExpect(MockMvcResultMatchers.status().isOk())
:返回响应状态是否为期望的200,如果不是则抛出异常andReturn()
:返回结果
package com.github.springboot.controller;
import com.github.springboot.domain.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.jupiter.api.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.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void userAdd() throws Exception{
User user = new User();
user.setName("test");
user.setAge(18);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/user")
.contentType(MediaType.APPLICATION_JSON)
.content(gson.toJson(user))
.accept(MediaType.APPLICATION_JSON))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
System.out.println(response.getStatus());
System.out.println(response.getContentAsString());
}
@Test
void userList() throws Exception{
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/user/list"))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
System.out.println(response.getStatus());
System.out.println(response.getContentAsString());
}
@Test
void deleteUser() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/user/"+1)).andExpect(MockMvcResultMatchers.status().isOk());
}
}