spring boot——MockMvc的用法
本篇避免长篇大论,依次说明:依赖、测试dao或service、测试controller、说明事项、附源码。
1、依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
2、测试dao、service
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-context.xml"})
public class ArticleServiceDaoTest2 {
@Autowired
private ArticleDao articleDao;
@Test
public void getAllListTest() {
List<Article> list=articleDao.getAllList();
for(Article article:list) {
System.out.println(article.getContent());
}
}
@Test
@Transactional
public void addTest() {
Article article = new Article();
article.setClassify("2");
article.setTitle("标题");
article.setContent("内容");
articleDao.insert(article);
}
@Test
public void addTest2() {
Article article = new Article();
article.setClassify("2");
article.setTitle("标题");
article.setContent("内容");
articleDao.insert(article);
}
}
3、测试controller
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-context.xml","classpath:spring-mvc.xml"})
@WebAppConfiguration
public class ArticleControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
@Before
public void setup(){
//加载web容器上下文
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
//返回json串
@Test
public void getByIdTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/article/getById")
.param("id", "15")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(15))
.andExpect(MockMvcResultMatchers.jsonPath("$.content").value("123456"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
//返回视图
@Test
public void detailTest() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/article/detail").param("id", "15"))
.andExpect(MockMvcResultMatchers.view().name("page/detail"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
Assert.assertNotNull(result.getModelAndView().getModel().get("article"));
}
//添加实体
@Test
public void addTest() throws Exception {
ResultActions resultActions = mockMvc.perform(
MockMvcRequestBuilders
.get("/article/add")//开始的斜杠不能丢,否则404
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("title", "测试用户1")
.param("classify", "123456")
.param("content", "123456"));
MvcResult mvcResult = resultActions
.andExpect(MockMvcResultMatchers.status().isOk()) //判断返回状态是否200
.andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("result:"+result);
}
//删除
@Transactional
@Test
public void deleteTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/article/delete")
.param("id", "15"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
说明事项:
(1)json-path:该jar包用于解析json,特别方便。
(2)测试service与测试dao类似:测试dao注入dao的bean;测试service注入service的bean。
(3)添加@Transactional注解,无论是否执行成功都会回滚事务,好处是不会污染数据库。
(4)测试Controller中路径不要忘了加斜杠如:/article/add(正确),article/add(错误)。
(5)测试dao、service与controller相同点都有注解@RunWith与@ContextConfiguration;不同点测试controller要加@WebAppConfiguration。
(6)注解@ContextConfiguration中的配置文件根据需要设置,例如测试controller要加spring-mvc.xml,测试dao和service则不需要。
附:源码类
ArticleDao.java
public interface ArticleDao {
void insert(Article article);
void delete(Integer id);
Article getById(Integer id);
List<Article> getListByParams(Article article);
List<Article> getAllList();
void update(Article article);
}
ArticleController.java
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping("/add")
@ResponseBody
public Result add(Article article) {
try {
articleService.add(article);
return new Result("添加成功!");
} catch (Exception e) {
return new Result("500","添加失败"+e);
}
}
@RequestMapping("/delete")
@ResponseBody
public Result delete(Integer id) {
try {
articleService.delete(id);
return new Result("删除成功!");
} catch (Exception e) {
return new Result("500","删除失败!"+e);
}
}
@RequestMapping("/getById")
@ResponseBody
public Article getById(Integer id) {
return articleService.getById(id);
}
@RequestMapping("/getListByParams")
@ResponseBody
public List<Article> getListByParams(Article article) {
return articleService.getListByParams(article);
}
@RequestMapping("/getAllList")
@ResponseBody
public List<Article> getAllList() {
return articleService.getAllList();
}
@RequestMapping("/update")
@ResponseBody
public Result update(Article article) {
try {
articleService.update(article);
return new Result("修改成功!");
} catch (Exception e) {
return new Result("500","修改失败!"+e);
}
}
@RequestMapping(value = "detail")
public String detail(Integer id, Model model) {
Article article = articleService.getById(id);
model.addAttribute("article", article);
return "page/detail";
}
}