赞
踩
MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。
controller
- @RestController
- public class IndexController {
-
- @RequestMapping("/index")
- public String index() {
- return "index";
- }
- }
测试controller
推荐文章: https://blog.csdn.net/vqhgWJl9EUB/article/details/78930280
package com.xxx.demo.controller; import org.junit.Before; import org.junit.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.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.abc.demo.controller.IndexController; @RunWith(SpringRunner.class) @SpringBootTest(classes=IndexController.class) @AutoConfigureMockMvc public class IndexControllerTest { @Autowired private MockMvc mockMvc; //初始化操作 @Before public void setUp(){ mockMvc=MockMvcBuilders.standaloneSetup(new IndexController()).build(); } @Test public void index() throws Exception{ mockMvc.perform(MockMvcRequestBuilders.get("/index") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。