Use PowerMock to extend Mockito so you are able to mock the static methods of FacesContext
.
If you are using Maven, use following link to check the needed dependency setup.
Annotate your JUnit test class using these two annotations. The first annotation tells JUnit to run the test using PowerMockRunner
. The second annotation tells PowerMock to prepare to mock the FacesContext
class.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ FacesContext.class })
public class PageBeanTest {
Mock FacesContext
using PowerMock. Use the Mockito verify()
method to make sure the addMessage()
method was called. Use an ArgumentCaptor
in order to retrieve the FacesMessage
that was passed to the addMessage()
method call on the FacesContext
. Then run assertEquals()
to check if the correct values where set to the FacesMessage
.
@Test
public void test() {
// mock all static methods of FacesContext
PowerMockito.mockStatic(FacesContext.class);
FacesContext facesContext = mock(FacesContext.class);
when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
MessageDisplayer messageDisplayer = new MessageDisplayer();
messageDisplayer.showMessage(FacesMessage.SEVERITY_INFO, "summary", "detail");
// create an ArgumentCaptor for the FacesMessage that will be added to
// the FacesContext
ArgumentCaptor<FacesMessage> facesMessageCaptor = ArgumentCaptor
.forClass(FacesMessage.class);
// verify if the call to addMessage() was made and capture the
// FacesMessage that was passed
verify(facesContext).addMessage(Mockito.anyString(),
facesMessageCaptor.capture());
// get the captured FacesMessage and check the set values
FacesMessage message = facesMessageCaptor.getValue();
assertEquals(FacesMessage.SEVERITY_INFO, message.getSeverity());
assertEquals("summary", message.getSummary());
assertEquals("detail", message.getDetail());
}
I've created a blog post which explains the above code sample in more detail.