Sunday, January 19, 2014

Mocking a Filter in Spring


Spring has provided the org.springframework.mock package for mocking various things in Spring. This is the unit test code that will mock the filter.



package com.test;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class ErrorHandlerMockTest {
        @Test
        public void testDoFilter() throws ServletException, IOException {
                MockHttpServletRequest request = new MockHttpServletRequest();
                MockHttpServletResponse response = new MockHttpServletResponse();
                MockFilterConfig config = new MockFilterConfig();
                
                FilterChain filterChain = new MockFilterChain() {
                        @Override
                        public void doFilter(ServletRequest req, ServletResponse res) {
                                throw new NullPointerException("test Filter");
                        }
                };
                
                ErrorHandler filter = new ErrorHandler();
                filter.init(config);
                filter.doFilter(request, response, filterChain);
                
                String contentAsString = response.getContentAsString();
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// ResponseInfo object is the custom object which will be returned as json response in filters
                ResponseInfo responseInfo = mapper.readValue(new StringReader(contentAsString), ResponseInfo.class);
                String errorCode = responseInfo.getResponseCode();
                Assert.assertEquals("ERR_CODE_000000", errorCode);
        }
}
Happy Coding!

No comments:

Post a Comment