我正在尝试使用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无法将任何请求发送到我的任何 Controller 。

我认为配置中有一些东西-contextConfigurationLocation。
看起来他可以找到该文件(否则它将引发异常),但是不加载任何配置

记录器说:

org.springframework.web.servlet.PageNotFound-找不到具有URI [http://localhost:8080/myapp/abc]的HTTP请求的映射

但是我绝对不知道怎么了...

我将不胜感激任何帮助!

提前致谢

最佳答案

地雷工作正常,请尝试以下调整。

  • (如果您使用的是Junit4,则无需扩展测试类),junit运行程序应该完成技巧
  • 通过类路径加载上下文配置,并确保可从测试类路径访问

    @ContextConfiguration(locations = {“classpath:applicationContext-test.xml”})
  • 然后只测试带注释的 Controller 。我是这样的:

  • @测试
    @交易
    公共(public)无效的testAnnotatedListUser()引发异常{
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    AnnotationMethodHandlerAdapter handlerAdpt =新的AnnotationMethodHandlerAdapter();
    request.setRequestURI(“/you/URIhere”);
    ModelAndView mav = handlerAdpt.handle(request,response,this.controller);
    assertEquals(“返回的 View 名称不正确”,“myexpectedviewname”,mav.getViewName());
    }

    10-07 19:42
    查看更多