admin管理员组

文章数量:1794759

Spring MVC单元测试

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请求的测试。

本文标签: 单元测试springMVC