Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking private field in servlet filter

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?

like image 209
Opal Avatar asked Dec 26 '22 12:12

Opal


1 Answers

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!

like image 148
Andrey Taptunov Avatar answered Jan 02 '23 20:01

Andrey Taptunov