前几天做在某个项目上做单元测试,始终报No mapping found for HTTP request with URI,报404
一通baidu,google,stackoverflow, 基本有以下几个原因
一、检查RequestBuilder的路径是否跟Controller里的一致
RequestBuilder request = MockMvcRequestBuilders.get("/corp-statistics/vm/download-corp-shop-daily-sales-v2")
二、检查ContextConfiguration里的参数是否有效
//测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根;
@WebAppConfiguration(value = "src/main/webapp")
@RunWith(SpringJUnit4ClassRunner.class)
//指定容器层次,即spring-config.xml是父容器,而spring-mvc.xml是子容器
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:spring-application.xml"),
@ContextConfiguration(name = "child", locations = "classpath:spring-mvc-servlet.xml")
})
//声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否
@Transactional
public class BaseTest {
@Autowired
private WebApplicationContext wac;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
@Before
public void setUp() throws Exception{
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
// mockMvc = MockMvcBuilders.standaloneSetup(new GoodNeighborController()).build();
}
}
网上有很多文章ContextConfiguration是这么定义的
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/*.xml"})
public class CDPlayerTest {
}
其中classpath的具体含义见:https://blog.csdn.net/linzhiji/article/details/104780126
这个地方我检查了很久,追溯MockMvc源码,发现根本没有遍历Controller,加入到RequestMappingHandlerMapping里,导致MockMvcRequestBuilders 处理的时候找不到对应的handle(具体Sping MVC初始化流程见https://blog.csdn.net/flowingflying/article/details/73368883)
我遇到的情况是,在启动Tomcat的时候,对应的URI是能找到Controller进行处理的,而单元测试的时候却不行
三、最终的问题
再次debug,发现MockMvc加载 ApplicationContext 没问题,就是没加载到ServletContext,
再回头看classpath,以及本项目的结构,发现项目中原来的Spring-mvc-servlet.xml是放在1位置的,没在Classptah(Resource)里,把Spring-mvc-servlet.xml挪到2
再改代码
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:spring-application.xml"),
@ContextConfiguration(name = "child", locations = "classpath:spring-mvc-servlet.xml")
})
这次终于可以。整整花了2天时间找这个问题。期间找到的文章https://blog.csdn.net/linzhiji/article/details/104743435