开发者

Can I attach filter for testing to httpunit ServletRunner?

开发者 https://www.devze.com 2023-02-11 06:37 出处:网络
I\'m using httpunit ServletRunner for servlets testing. Now I want to test servlet which uses request attributes (not parameters). Attributes are put to the request by my filter. So for servlet to wor

I'm using httpunit ServletRunner for servlets testing. Now I want to test servlet which uses request attributes (not parameters). Attributes are put to the request by my filter. So for servlet to work properly, there has to be filter installed.

Is there some way to add filter to Servlet开发者_开发问答Runner?


I don't think that can be done. HttpUnit does not provide setAttribute method for WebRequest, which makes sense, since attributes can only be set from within the container.

However, what you can do (and possibly even should) is to test both individually in separate tests - that filter puts the parameters to the request, and servlet works if parameters are set up correctly. The way to do it would be creating a mock request for the servlet, setting the attributes for that, and running a regular unit test for that. Same approach applies for the filter.

Here's an example of doing it with a filter:

@Test
public void testDefaultRequestEncoding() throws ServletException, IOException {
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding(CONFIGURED_ENCODING_UTF8);
    filter.setForceEncoding(ENFORCE_ENCODING_TRUE);

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = new MockFilterChain();

    request.setCharacterEncoding(TEST_ENCODING_ISO_8859_15);

    filter.doFilter(request, response, filterChain);

    assertEquals(CONFIGURED_ENCODING_UTF8, request.getCharacterEncoding());
    assertEquals(CONFIGURED_ENCODING_UTF8, response.getCharacterEncoding());
}

Mock* objects are from Spring. If your framework does not have them, you can create them by using some mock library, or use the ones that can be seen from Spring sources.


It looks like

com.meterware.servletunit.WebApplication has registerFilters(...).
Need to instantiate with:
ServletRunner( File yourTestWebXml_WithFilter )

Make sure you declare at least 1 servlet, before testing any filters in your test web.xml.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号