我有一个过滤器类,叫做SomeFilter
它实现javax.servlet.Filter
。在 doFilter 方法中,我使用键“key”和值“result”设置了属性“someResult”。
我有一个名为的单元测试类TestSomeFilter
,它调用SomeFilter
. 现在的问题是我在过滤器中设置的请求属性“someResult”没有设置。这仅在我进行单元测试(在本地)时发生,即请求是模拟请求。如果我在 websphere 应用程序服务器(本地)上部署过滤器,则属性设置正确。MockedRequestWrapper
此外,当我在调试模式下运行单元测试时,不会调用setAttribute 。
代码如下。
如果有人可以通过为我的问题提供解决方案或至少为我指出正确的方向来帮助我,我将不胜感激。
提前致谢!
代码:
public class SomeFilter implements javax.servlet.Filter {
public void doFilter(ServletRequest req,
ServletResponse res, FilterChain chain)
throws ServletException {
//do some stuff
HttpServletRequest request = (HttpServletRequest) req;
Map<String,String> map = new HashMap<String,String>();
map.put("key","result");
request.setAttribute("someResult",map);
chain.doFilter(request, res);
}
}
public class TestSomeFilter {
@org.junit.Test
public void testSomeFilter {
HttpServletRequest mockRequest = null;
HttpServletResponse mockResponse = null;
HttpSession mockSession = null;
MockedRequestWrapper mrw = null;
org.easymock.EasyMock.replay(mockSession);
org.easymock.EasyMock.replay(mockRequest);
org.easymock.EasyMock.replay(mockResponse);
mrw = new MockedRequestWrapper(mockRequest);
filter.doFilter(mrw, mockResponse, mockFilterChain);
HashMap<String,String> map = (HashMap<String,String>) mrw
.getAttribute(("someResult");
String value = map.get("key");
org.junit.Assert.assertEquals(
"The output should be result.",
"result", value);
}
@org.junit.Before
public void setUp() throws Exception {
mockRequest = createNiceMock(HttpServletRequest.class);
mockResponse = createNiceMock(HttpServletResponse.class);
mockSession = createNiceMock(HttpSession.class);
}
@org.junit.After
public void tearDown() throws Exception {}
public class MockedFilterChain implements FilterChain {
public void doFilter(ServletRequest request,
ServletResponse response)
throws ServletException {}
}
}
public class MockedRequestWrapper extends HttpServletRequestWrapper {
private Map<String,Object> m = null;
public MockedRequestWrapper(HttpServletRequest httpServletRequest) {
super(httpServletRequest);
}
public void setAttribute(String name, Object o){
m = new HashMap<String,Object>();
m.put(name, o);
}
public Object getAttribute(String name){
return m.get(name);//<<<< PROBLEM: This map is always null causing NPE
}
}