How can you test methods that contain static method calls? This is a question we’re facing at the moment while working on an application of which parts have been written by another development team. In order to gain insight into functionality and quality of the codebase, we are writing JUnit tests. But a lot of the code is dependent on either the JSF FacesContext or the Spring ApplicationContext being available.

It is however impossible to mock static method calls like FacesContext.getCurrentInstance(). So how do we go around testing these calls out of container? We’ve thought up three different approaches, but each has its pros and cons. Let us first take a look at these three approaches…

1. Extract method
Introduce a method in each class that looks like the following:

This can be easily mocked out in your test by creating the class with an overridden method, as follows:


  • Easy to refactor using extract method


  • Lots of code duplication

2. Static Helper
Our second option is to introduce a static helper class which has the following implementation:

Now in a testclass we can just write down the following line to mock out the FacesContext:


  • No real painful code-duplication
  • Easy to do search-replace to convert all calls to FacesContext.getCurrentInstance() to FacesContextHelper.getCurrentFacesContext().


  • Never forget to call reset() in the teardown of your test to prevent another test from picking up your mock.
  • Doesn’t feel right to write static setter methods in your code just to enable testing it. Not an OO approach?

3. OO Helper class
Our third and last option is to introduce an interface and implementation of the FacesContextHelper:

We now need to introduce an instance of the FacesContextHelperImpl to each class. For this example, we will use a package protected variable in each class. It is of course also possible to use a setter method. For our test cases we now need to introduce a new FacesContextHelper:

In our test cases we can now easily mock out the FacesContext again by setting the package protected field:


  • Feels more natural and OO than the static helper solution


  • Need to introduce a new field to each and every class which needs the FacesContext mocked out.

That’s it. I myself am still doubting as to which method is the lesser evil, not one feels absolutely right. What do you think, which method do you consider better? Did I overlook another option perhaps?