例如,您可以使用PowerMock,它是一个允许您扩展Mockito等具有额外功能的模拟库的框架。在这种情况下,它允许您模拟FacesContext
.
使用Mockito verify()
方法,您可以确保addMessage()
调用了该方法。此外,您可以使用 anArgumentCaptor
来检索FacesMessage
传递addMessage()
给FacesContext
.
@Test
public void testToPage2NotChecked() {
// mock all static methods of FacesContext
PowerMockito.mockStatic(FacesContext.class);
FacesContext facesContext = mock(FacesContext.class);
when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
NavigationBean navigationBean = new NavigationBean();
navigationBean.setCheck(false);
// check the returned value of the toPage2() method
assertEquals("", navigationBean.toPage2());
// 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("Sæt i kryds checkboxen", message.getSummary());
}
我创建了一篇博文,更详细地解释了上述代码示例。