gpt4 book ai didi

java - ServletRequest过滤器测试用例

转载 作者:行者123 更新时间:2023-12-02 05:09:09 25 4
gpt4 key购买 nike

我有一个看起来像这样的过滤器:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

// Get the servlet request
HttpServletRequest req = (HttpServletRequest) request;

... Some logic code here ...

if (!accepted.contains(req.getRequestURI())) {
HttpServletResponse res = (HttpServletResponse) response;
res.sendError(404, "Some Error");
return;
}

// Pass the request along the filter chain
chain.doFilter(request, response);
}

问题出在我的测试用例上。通常我会使用mockito来模拟HttpServletRequest,如下所示:

HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("the test URI");

但是,事实上 HttpServletRequest 是通过在方法内部通过强制转换获得的,我不确定测试各种 URI 请求的最佳方法。

最佳答案

您应该仍然能够使用 doFilter 调用您的 servlet,如下所示:

HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("the test URI");
HttpServletResponse response = mock(HttpServletResponse.class);
//mock method calls on response, replay
myServlet.filter(request, response);

即使它在内部进行类型转换也没关系。

关于java - ServletRequest过滤器测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com