Mocking FacesContext

mkoryak picture mkoryak · Nov 23, 2010 · Viewed 24.6k times · Source

I am trying to add some unit tests to a JSF application. This application didnt rely heavily on any best practices, so many service methods use the FacesContext to pull data from managed session beans like so:

(this is inside a util class)

  public static Object getPageBean(String beanReference) {
      FacesContext fc = FacesContext.getCurrentInstance();
      VariableResolver vr = fc.getApplication().getVariableResolver();
      return vr.resolveVariable(fc, beanReference);
  }

What would be the best way to mock this? I am using groovy so i have a few more options for creating classes that i cant normally create.

Answer

McDowell picture McDowell · Jan 26, 2012

You can return a mock context via FacesContext.getCurrentInstance by invoking setCurrentInstance(FacesContext) before running the test. The method is protected, but you can access it either via reflection or by extending FacesContext. There is a sample implementation using Mockito here.