Sunday, January 19, 2014
Mocking a Filter in Spring
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 {@Testpublic void testDoFilter() throws ServletException, IOException {MockHttpServletRequest request = new MockHttpServletRequest();MockHttpServletResponse response = new MockHttpServletResponse();MockFilterConfig config = new MockFilterConfig();FilterChain filterChain = new MockFilterChain() {@Overridepublic 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 filtersResponseInfo responseInfo = mapper.readValue(new StringReader(contentAsString), ResponseInfo.class);String errorCode = responseInfo.getResponseCode();Assert.assertEquals("ERR_CODE_000000", errorCode);}}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment