Spring 3.0 junit test DispatcherServlet
作者:互联网
我试图用junit测试我的应用程序.
因此我设置了以下类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/META-INF/spring/applicationContext-test.xml" )
@TransactionConfiguration
@Transactional
public class DispatcherServletTest extends AbstractJUnit4SpringContextTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private DispatcherServlet dispatcher;
@Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
MockServletConfig config = new MockServletConfig("myapp");
config.addInitParameter("contextConfigLocation","classpath*:webmvc-config.xml");
dispatcher = new DispatcherServlet();
dispatcher.init(config);
}
//test cases
}
所以问题是,我的调度程序servlet似乎无法向我的任何控制器发送任何请求.
我认为配置有一些东西–contextConfigurationLocation.
看起来他可以找到该文件(否则会引发异常),但不会加载任何配置
记录器说:
org.springframework.web.servlet.PageNotFound – 找不到带URI的HTTP请求的映射[http:// localhost:8080 / myapp / abc]
但我完全不知道出了什么问题……
我将不胜感激任何帮助!
提前致谢
解决方法:
矿井工作正常,尝试以下调整.
>如果您正在使用Junit4而不需要扩展测试类,那么junit runner应该可以解决问题
>通过类路径加载上下文配置,并确保可以从测试类路径访问
@ContextConfiguration(位置= { “类路径:的applicationContext-的test.xml”})
>然后只测试带注释的控制器.我是这样做的:
@Test @Transactional public void testAnnotatedListUser() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); AnnotationMethodHandlerAdapter handlerAdpt = new AnnotationMethodHandlerAdapter(); request.setRequestURI("/you/URIhere"); ModelAndView mav = handlerAdpt.handle(request, response, this.controller); assertEquals("Incorrect view name returned", "myexpectedviewname", mav.getViewName()); }
标签:junit4,spring,spring-3,dispatcher 来源: https://codeday.me/bug/20190709/1417971.html