Spring MVC Controller单元测试

发表于:2014-11-19 13:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:pairwinter    来源:51Testing软件测试网采编

  可以看到分开配置,使得文件的作用更加的明了。
  这部分的配置文件是来配置web context 的,项目中还有其他的module ,如DAO,Service,他们对应的applicationContext文件会被放在src/main/resource目录下。
  完善的单元测试当然还有service的单元测试,这里就不说了,但是Controller的单元测试还需要调用service和DAO,要注意Service和DAO的applicationContext的引入。
  Controller 单元测试
  在测试类中包含这三个注释,看起表面意思不难理解他们的作用,主要理解ContextConfiguration的使用。
  @RunWith(SpringJUnit4ClassRunner.class)
  @WebAppConfiguration //默认是src/main/webapp
  @ContextConfiguration("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")
  注意:这里的@ContextConfiguration只解析了servlet-context.xml,如果项目中还存在其他模块的applicationContext,也需要把他们引进来否则得到的Service就是null的。
  例如
  @ContextConfiguration({
  "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml",
  “classpath*: springxml/**.xml”
  })
  在加上其他的一点代码就可以完成一个Controller的单元测试,下面是一个例子,更多例子请参考showcase中的内容。
package pairwinter.spring.mvc.controller.test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.samples.mvc.AbstractContextControllerTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml",
“classpath*: springxml/**.xml”
})
public class ControllerTests{
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void controllerExceptionHandler() throws Exception {
this.mockMvc.perform(get("/test"))
.andExpect(status().isOk());
}
}
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号