Is is possible to mock (currently using Mockito, may be also other testing lib) the field 'sf' in the class shown below:
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("");
}
}
If so, how?
Consider PowerMock framework with some nifty features, including some integration with Mockito framework
Consider this example to bypass encapsulation and access private field, like below
String sf = Whitebox.getInternalState(o, "sf", String.class, B.class);
Whitebox.setInternalState(o, "sf", "XXX", B.class);
Also consider (from the last link):
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With