Spring 3.0 junit test DispatcherServlet

I am trying to test my application using junit.

So I installed the following class:

@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 

}

So the problem is that my dispatcher servlet cannot send any request to any of my controllers.

I think there is something with the configuration - contextConfigurationLocation. It looks like it can find the file (otherwise it will throw an exception), but does not load the configuration

Logger says:

org.springframework.web.servlet.PageNotFound - no mapping found for HTTP request with URI [http: // localhost: 8080 / myapp / abc]

But I absolutely do not know what happened ...

I would be grateful for any help!

Thank you in advance

+4
source share
2 answers

The mines are working fine, try the following settings.

  • If you are using Junit4 you do not need to extend the test class, junit runner should do the trick
  • Download the context configuration through the class path and make sure that it is accessible from the test class path

    @ContextConfiguration (places = {"classes: ApplicationContext-test.xml"})

  • then just check annotated controllers. I do it like this:

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

+1
source

There are several issues in my question:

Firstly, it is not possible to extend AbstractJUnit4SpringContextTests and use @RunWith (...) because it is the same.

Secondly, you should not use the Serverlert dispatcher, but a handler, defining a handler in your .xml application and automatically installing it in a test case using the private Handler @Autowire ... handler ...

Then everything should work fine!

0
source

All Articles