Friday, January 21, 2011

Spring mvc 3 junit test

Below is a code snippet to easily test a spring annotated web controller


public abstract class BaseWebControllerTest {
    @Autowired
    protected ApplicationContext context;
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected HandlerAdapter handlerAdapter;

    public void before() {
        handlerAdapter = context.getBean(HandlerAdapter.class);
    }
   
    void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        final HandlerMapping handlerMapping = context.getBean(HandlerMapping.class);
        final HandlerExecutionChain handler = handlerMapping.getHandler(request);
        assertNotNull("No handler found for request, check you request mapping", handler);

        final Object controller = handler.getHandler();

        final HandlerInterceptor[] interceptors = handlerMapping.getHandler(request).getInterceptors();
        for (HandlerInterceptor interceptor : interceptors) {
            final boolean carryOn = interceptor.preHandle(request, response, controller);
            if (!carryOn) {
                return;
            }
        }

        handlerAdapter.handle(request, response, controller);
    }

}


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/test-app-config.xml")

public class MyControllerTest extends BaseWebControllerTest{
    MyController controller;

    @Before
    public void before() {
        super.before();
        controller = context.getBean(MyController.class);
    }

    @Test
    public void testGetRestRequest() throws Exception {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
       
        request.setContentType("application/json");
        request.setMethod("GET");
        request.setRequestURI("/rule/"+id);

        handle(request, response);
       
        String result =response.getContentAsString();
        logger.info("RESULT : "+result);
        //assert json response is right.
    }
}

Reference:
http://efreedom.com/Question/1-2314377/Testing-Spring-MVC-Annotations

No comments: