简体   繁体   中英

Unit test for Filter class

I am trying to write unit tests for the following Filter class, but I am not sure how it can be done. I am working on a Spring project and trying to fix a vulnerability, that is why I am using this class.

public class HSTSFilter implements Filter {
    private static final String HEADER_NAME = "Strict-Transport-Security";
    private static final String MAX_AGE_DIRECTIVE = "max-age=%s";
    private static final String INCLUDE_SUB_DOMAINS_DIRECTIVE = "includeSubDomains";
    private static final Logger logger = LoggerFactory.getLogger(HSTSFilter.class);

    private int maxAgeSeconds = 0;
    private boolean includeSubDomains = false;
    private String directives;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        logger.info("request.isSecure() :: {}" , request.isSecure());

        if (request.isSecure() && response instanceof HttpServletResponse) {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader(HEADER_NAME, this.directives);
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        maxAgeSeconds = Integer.parseInt(filterConfig.getInitParameter("maxAgeSeconds"));
        includeSubDomains = "true".equals(filterConfig.getInitParameter("includeSubDomains"));

        if (this.maxAgeSeconds <= 0) {
            throw new ServletException("Invalid maxAgeSeconds value :: " + maxAgeSeconds);
        }

        this.directives = String.format(MAX_AGE_DIRECTIVE, this.maxAgeSeconds);
        if (this.includeSubDomains) {
            this.directives += (" ; " + INCLUDE_SUB_DOMAINS_DIRECTIVE);
        }
    }

    @Override
    public void destroy() {
    }
}

In your unit test, create a mock object of ServletRequest, ServletResponse, and FilterChain. Call doFilter with these mock objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM