模拟FacesContext来测试我的面部消息显示器类

时间:2014-10-29 13:53:07

标签: maven jsf junit mockito facescontext

我的支持豆:

@ManagedBean(name = "messageDisplayer")
@ViewScoped
public class MessageDisplayer implements Serializable
{
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    public void showMessage (FacesMessage.Severity severity, String summary, String detail)
    {
        FacesContext context = FacesContext.getCurrentInstance();
        LOGGER.debug("Showing message with severity='{}', summary='{}', detail='{}'", severity, summary, detail);
        context.addMessage(null, new FacesMessage(severity, summary, detail));
    }
}

有关如何使用Mockito测试此课程的任何帮助!?

2 个答案:

答案 0 :(得分:2)

使用 PowerMock 扩展 Mockito ,以便您可以模拟FacesContext的静态方法。

如果您使用的是Maven,请使用以下link检查所需的依赖关系设置。

使用这两个注释注释您的JUnit测试类。第一个注释告诉JUnit使用PowerMockRunner运行测试。第二个注释告诉 PowerMock 准备模拟FacesContext类。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ FacesContext.class })
public class PageBeanTest {

使用 PowerMock 模拟FacesContext。使用 Mockito verify()方法确保调用addMessage()方法。使用ArgumentCaptor来检索传递给FacesMessage上的addMessage()方法调用的FacesContext。然后运行assertEquals()以检查设置为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());
}

我创建了一个blog post,更详细地解释了上面的代码示例。

答案 1 :(得分:0)

您应该使用PowerMock来模拟静态方法。 以下是如何使用它的示例:https://code.google.com/p/powermock/wiki/MockStatic