可以看到分开配置,使得文件的作用更加的明了。
这部分的配置文件是来配置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()); } } |