Mockito - Unit Testing FacesContext using PowerMock, JUnit and Maven

JSF defines the FacesContext abstract base class for representing all of the contextual information associated with processing an incoming request and creating the corresponding response. When writing unit test cases for a JSF application there might be a need to mock some of the FacesContext static methods.

The following post will illustrate how to do this using PowerMock, a framework that allows you to extend mock libraries like Mockito with extra capabilities. In this case the capability to mock the static methods of FacesContext.

Tools used:

JUnit 4.11

Mockito 1.10

PowerMock 1.5

Maven 3.5

The code sample is built and run using Maven. Specified below is the Maven POM file which contains the needed dependencies for JUnit, Mockito, and PowerMock. In addition the PowerMock support module for JUnit powermock-module-junit4 and the PowerMock API for Mockito powermock-api-mockito dependencies need to be added as specified below.

As the FacesContext class is used in this code sample, dependencies to the EL (Expression Language) API and JSF specification API are also included.

The SomeBean class below contains two methods that make use of FacesContext. The first addMessage() method will create a new FacesMessage and add it to the FacesContext. The second logout() method will invalidate the current session.

The SomeBeanTest JUnit test class is used to test the above. The class is annotated using two annotations. The first @RunWith annotation tells JUnit to run the test using PowerMockRunner. The second @PrepareForTest annotation tells PowerMock to prepare to mock the FacesContext class. If there are multiple classes to be prepared for mocking, they can be specified using a comma-separated list.

In the setup() method a number of objects are specified that are similar for the two test cases. The mockStatic() method is called in order to tell PowerMock to mock all static methods of the given FacesContext class. We then use the when() method to specify what instance to return in case the getCurrentInstance() method is called on FacesContext. The same is done for the getExternalContext() method.

Note that because of the 'org.mockito.Mockito.when' import there is no Mockito class name in front of the static when() method.

The first addMessage() test case uses the ArgumentCaptor capability of Mockito in order to test whether a FacesMessage with the correct values was added to the FacesContext. The second testLogout() test case checks if the correct redirect was returned.

packagecom.codenotfound.mockito;importstaticorg.junit.Assert.assertEquals;importstaticorg.junit.Assert.assertNull;importstaticorg.mockito.Mockito.verify;importstaticorg.mockito.Mockito.when;importjavax.faces.application.FacesMessage;importjavax.faces.context.ExternalContext;importjavax.faces.context.FacesContext;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.mockito.ArgumentCaptor;importorg.mockito.Mock;importorg.powermock.api.mockito.PowerMockito;importorg.powermock.core.classloader.annotations.PrepareForTest;importorg.powermock.modules.junit4.PowerMockRunner;@RunWith(PowerMockRunner.class)@PrepareForTest({FacesContext.class})publicclassSomeBeanTest{privateSomeBeansomeBean;@MockprivateFacesContextfacesContext;@MockprivateExternalContextexternalContext;@BeforepublicvoidsetUp()throwsException{someBean=newSomeBean();// mock all static methods of FacesContext using PowerMockitoPowerMockito.mockStatic(FacesContext.class);when(FacesContext.getCurrentInstance()).thenReturn(facesContext);when(facesContext.getExternalContext()).thenReturn(externalContext);}@TestpublicvoidtestAddMessage(){// create Captor instances for the clientId and FacesMessage parameters// that will be added to the FacesContextArgumentCaptor<String>clientIdCaptor=ArgumentCaptor.forClass(String.class);ArgumentCaptor<FacesMessage>facesMessageCaptor=ArgumentCaptor.forClass(FacesMessage.class);// run the addMessage() method to be testedsomeBean.addMessage(FacesMessage.SEVERITY_ERROR,"error","something went wrong");// verify if the call to addMessage() was made and capture the argumentsverify(facesContext).addMessage(clientIdCaptor.capture(),facesMessageCaptor.capture());// check the value of the clientId that was passedassertNull(clientIdCaptor.getValue());// retrieve the captured FacesMessageFacesMessagecaptured=facesMessageCaptor.getValue();// check if the captured FacesMessage contains the expected valuesassertEquals(FacesMessage.SEVERITY_ERROR,captured.getSeverity());assertEquals("error",captured.getSummary());assertEquals("something went wrong",captured.getDetail());}@TestpublicvoidtestLogout(){assertEquals("logout?faces-redirect=true",someBean.logout());}}

In order to run the above test cases, open a command prompt and execute following Maven command:

mvn test

If you would like to run the above code sample you can get the full source code here.

This concludes the mocking FacesContext using Mockito and PowerMock example. If you found this post helpful or have any questions or remarks, please leave a comment.