java - 在 servlet 过滤器中模拟私有(private)字段

标签 java servlets servlet-filters mockito

是否可以模拟(当前使用 Mockito,也可能是其他测试库)下面所示类中的字段“sf”:

public class SomeFilter implements Filter {

   private Logger log = Logger.getLogger(getClass());
   private SomeField sf = new SomeField();

   @Override
   public void init(FilterConfig fc) throws ServletException {
      log.info("");
   }

   @Override
   public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws     IOException, ServletException {
        fc.doFilter(request, response);
   }

   @Override
   public void destroy() {
      log.info("");
   }
}

如果是,怎么做到的?

最佳答案

考虑 PowerMock具有一些漂亮功能的框架,包括 some integration with Mockito framework

考虑 this example绕过封装并访问私有(private)字段,如下所示

String sf = Whitebox.getInternalState(o, "sf", String.class, B.class);
Whitebox.setInternalState(o, "sf", "XXX", B.class);

还要考虑(来自最后一个链接):

All of these things can be achieved without using PowerMock, this is just normal Java reflection. However reflection requires much boiler-plate code and can be error prone and thus PowerMock provides you with these utility methods instead. PowerMock gives you a choice on whether to refactor your code and add getter/setter methods for checking/altering internal state or whether to use its utility methods to accomplish the same thing without changing the production code. It's up to you!

关于java - 在 servlet 过滤器中模拟私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13948807/

相关文章:

java - 当经过身份验证的用户访问未 protected 页面时,getRemoteUser() 返回 null

java - 如何让Javamelody使用不同的端口(Spring Boot+暴露的两个HTTP端口)

java - 通过独立应用程序进行图像处理

java - 正在编码的 AttributeModifier 模型

java - 根据主体tomcat重定向请求

html - 表行上的单选按钮组

java - 自定义过滤器不读取属性文件,该文件放置在使用该过滤器的 WEB 应用程序中

spring - Servlet 过滤器修改 header 值,而 servlet 请求包装器不起作用

java - BufferedImage 报告不正确的颜色模型类型

java - 终止无限循环会卡住终端