概述
JUnit 是一个用于编写可重复测试的简单框架。它是用于单元测试框架的 xUnit 架构的一个实例。
MockMVC 基于RESTful风格的SpringMVC单元测试,可以测试完整的SpringMVC流程,即从URL请求到控制处理器,带到视图渲染都可以测试。
项目依赖
- JDK 1.8
- SpringBoot 2.5.1
- MybatisPlus 3.4.3.1
Junit 测试
maven 依赖
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
控制器类
@Api(tags = "用户控制器",value = "提供用户服务")
@RestController
public class UserController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
UserService userService;
/**
* 查询用户
* @param username
* @return
*/
@ApiOperation(value="查询用户", notes="通过用户名获取用户")
@GetMapping(value="/getUsers", produces = "application/json;charset=UTF-8")
public ResultData getUsers(@RequestParam String username){
logger.info(" get user,params username : {}",username);
boolean result = true; // userService.getUsers(user);
if(result)
return ResultData.ok();
else
return ResultData.error();
}
/**
* 保存用户
* @param user
* @return
*/
@ApiOperation(value="保存用户", notes="通过用户名保存用户")
@PostMapping(value="/saveUser", produces = "application/json;charset=UTF-8")
public ResultData saveUser(@RequestBody User user){
logger.info(" save user,params username : {}",user.getUsername());
boolean result = true; // userService.saveUser(user);
if(result)
return ResultData.ok().message("保存成功");
else
return ResultData.error().message("保存失败!");
}
}
User 实体
@Data
public class User {
private Long userid;
private String username;
private String password;
}
测试类
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
public class UserApplicationTests {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
}
/**
* 测试查询方法
* @throws Exception
*/
@Test
public void testGet() throws Exception {
User user = new User();
user.setUserid(0L);
user.setUsername("Jack");
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/getUsers")
.contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8")
.content(JSON.toJSONString(user))
.param("username", "Jack")
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
assertEquals(HttpStatus.OK.value(), 200);
String content = mvcResult.getResponse().getContentAsString();
assertEquals("{\"success\":true,\"code\":200,\"message\":\"成功!\",\"data\":{}}", content);
}
/**
* 测试保存方法
* @throws Exception
*/
@Test
public void testSave() throws Exception {
User user = new User();
user.setUserid(1L);
user.setUsername("Jack");
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/saveUser")
.contentType(MediaType.APPLICATION_JSON)
.content(JSON.toJSONString(user))
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), 200);
assertEquals("{\"success\":true,\"code\":200,\"message\":\"保存成功\",\"data\":{}}", content);
}
}
测试
右键执行对应方法测试,返回结果:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json;charset=UTF-8"]
Content type = application/json;charset=UTF-8
Body = {"success":true,"code":200,"message":"保存成功","data":{}}
Forwarded URL = null
Redirected URL = null
Cookies = []
参考
https://junit.org/junit4/
https://spring.io/guides/gs/testing-web/
https://javadoc.io/static/org.mockito/mockito-core/3.11.2
/org/mockito/Mockito.html