czwartek, 13 grudnia 2012

Spring examples #2 - Testing Controller using Spring MVC with session scope

Sometimes there is need to store user session data in a session object. There are two choices for that. We can add session scope to a specific object or to whole controller. For testing purposes it is easier (however, not better) to choose the second option. Let us add some annotations to controller:
@Controller
@Scope("session")
public class MyController {

 @Autowired
 SomeSingletonFromContext singleton;

 SessionObject sessionObject = new SessionObject();

 @RequestMaping("/my.htm")
 public void myRequest(HttpServletRequest, HttpServletResponse) {
  ServletOutputStream out = response.getOutputStream();
  response.setContentType("application/json");
  response.setHeader("Cache-Control", "no-cache");
  out.print("Hello Session User");
 }
}
In the tricky part we will enable session for testing. The context configuartion below is our "access point" for controller testing class. Note the 'import' tag pointing to default servlet configuration.



  
      
          
              
                  
              
          
      
  

  


In the servlet-context we need to scan for controller:



Finally we have to set up our test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
 "file:path/to/test-context-as-above.xml"})
public class MyControllerTest {
 
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    
    @Autowired
    private MyController myController;
 
    @Before
    public void setUp() {
     request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();        
    }

    @Test
    public void testSubmit() throws Exception {

     request.setMethod("POST");
        request.setRequestURI("/my.htm");
        request.addParameter("param", "value");
        
        @SuppressWarnings("unused")
        final ModelAndView mavBack = new AnnotationMethodHandlerAdapter()
            .handle(request, response, controller);
        
        assertEquals(response.getContentType(), "application/json");

    }
}
That's all.