是否可以模拟(当前使用 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/