admin管理员组文章数量:1794759
Spring MVC单元测试
Spring MVC单元测试
Spring mvc 测试框架是基于Servlet API mock对象(在spring 的org.springframework.mock.web包中提供),因此无需使用运行时servlet容器。
测试类配置测试类需要通过注解进行配置,示例代码如下:
import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.ContextConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = MyWebConfig.class) public class MyMvcControllerTest { .... }@RunWith是JUnit的注解,指定SpringJUnit4ClassRunner覆盖确实的org.junit.runners.BlockJUnit4ClassRunner,其也是BlockJUnit4ClassRunner的子类。
@WebAppConfiguration用于指定为测试加载WebApplicationContext.
@ContextConfiguration用于指定怎么加载spring bean的元数据。上面示例我们指定从MyWebConfig类中加载。
设置@Before对象在Before注解的方法中,我们需要初始化spring特定的mock对象:MockMvc,spring mvc服务器端测试支持的主入口。
public class MyMvcControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac); this.mockMvc = builder.build(); } }MockMvcBuilders 是访问特定MockMvcBuilder的实现接口的主要类。
写@Test测试方法这里我们需要两个builder 类的协助:
MockMvcRequestBuilders: 用于构建 MockHttpServletRequest。
MockMvcResultMatchers: 用于构建 ResultMatcher ,描述匹配执行请求期望返回结果。
@Test public void testMyMvcController() throws Exception { ResultMatcher ok = MockMvcResultMatchers.status().isOk(); ResultMatcher msg = MockMvcResultMatchers.model() .attribute("msg", "Spring quick start!!"); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/"); this.mockMvc.perform(builder) .andExpect(ok) .andExpect(msg); }需要测试的Controller类如下:
@Controller public class MyMvcController { @RequestMapping(value = "/", method = RequestMethod.GET) public String prepareView(Model model) { model.addAttribute("msg", "Spring quick start!!"); return "my-page"; } } 总结本文介绍了spring mvc 的web请求测试,通过spring mvc提供的mock对象,可以无需servlet运行时容器进行测试。
除了spring test的基本配置以外,还需要添加@WebAppConfiguration,用于加载WebApplicationContext.测试前先在@Before方法中初始化MockMvc mockMvc。最后在两个builder类的辅助下可以完成web请求的测试。
版权声明:本文标题:Spring MVC单元测试 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686614400a86345.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论