2011-10-20 79 views
4

我想用junit测试我的应用程序。Spring 3.0 junit测试DispatcherServlet

所以我设置了以下类:

@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://本地主机:8080/MyApp的/ ABC]

但我根本不知道什么是错的......

我希望得到任何帮助!

在此先感谢

+1

您真的想测试调度程序servlet吗,为什么不测试Web控制器处理程序方法? – Ralph

+0

我认为我们无法使用junit测试http请求。只有服务。 – jaleel

+0

不,如果调用正确的控制器方法,我真的会测试整个应用程序的含义。 例如: 我发送POST到/ myposturl并将一些数据发送到后端,并且想要检查负责此调用的方法的正确控制器是否正在“回答” 所以我认为是,我必须发送请求调度程序servlet而不是直接控制器。 在我的控制器我只是有处理此请求的方法: RequestMapping(method = RequestMethod.POST,headers =“Accept = ...”) public ResponseEntity createFromJsonArray(@RequestBody String json){... – Alexander

回答

1

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

  1. 如果你使用Junit4不需要扩展你测试类的JUnit运行应该做的伎俩
  2. 通过加载的类路径配置方面,并确保从测试类路径访问

    @ContextConfiguration(locations = {“classpath:applicationContext-test.xml”})

  3. 然后只是测试注释的控制器。我不喜欢这样写道:

 

    @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()); 
    } 

0

有我的问题了几个问题:

起初,它是不可能延长AbstractJUnit4SpringContextTests时和使用@RunWith(...),因为一样的。

在第二,你不应该在你的Application.xml定义的处理程序,并在通过@Autowire私人处理程序处理程序测试用例自动装配它使用dispatcherServlert,而是一个处理器...

然后,一切都应该工作精细!