如何使用JUnit

时间:2016-05-30 15:19:51

标签: java unit-testing junit junit4

中止() - 方法:

public void abort() {
    LOG.info("some-text");
    warning("some-text");
}

警告() - 方法:

 public void warning(String message) {
    FacesContext.getCurrentInstance()
.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "INFO:", message));
}

我想编写一个中止的测试用例,它只是验证没有任何变化,第二个测试用例验证 warning()是否正常工作。 我知道这两个方法不需要单元测试,但我想知道它是否可行。用于显示p:消息的UI-Test运行良好但我想先检查Captest,Typ和Message by Unittest,因为它运行得更快。

1 个答案:

答案 0 :(得分:1)

使用JUnit 4.11的工作解决方案

在自己的类中将内容与warning()分开,如下所示:

@Named
@RequestScoped
public class Resources {
       @Produces
       public FacesContext produceFacesContext() {
              return FacesContext.getCurrentInstance();
       }
}

接下来,您需要定义一个ArgumentCaptor,它可以为您的JUnit-Test捕获FacesMessage。我创建了一个clss成员,它将在@before部分初始化并在@teardown中获取null值。

private ArgumentCaptor<FacesMessage> facesMessageCaptor;
@Before
public void setUp() {facesMessageCaptor = ArgumentCaptor
            .forClass(FacesMessage.class);
}
@After
public void tearDown() { facesMessageCaptor = null; }

现在您只需要在测试类中添加两个@Mocks

@Mock
Resources resourcesMock; 
@Mock
FacesContext facesContextMock;

所以你做到了!像这样写测试:

Mockito.doReturn(facesContextMock).when(resourcesMock).produceFacesContext();
// Execute Method
cut.warning("SOME_DETAIL_TEXT");
// Verify interactions with the Resources and Faces and maybe others...
verify(resourcesMock).produceFacesContext();
verify(facesContextMock).addMessage(Mockito.anyString() ,
                facesMessageCaptor.capture());
verifyNoMoreInteractions(...., resourcesMock, facesContextMock);
// write assert (i´ve used hamcrast-corematchers - more readable)
actualMessage = (FacesMessage) facesMessageCaptor.getValue();
assertThat(FacesMessage.SEVERITY_WARN, is(equalTo(actualMessage.getSeverity())));
assertThat(MY_TITLE, is(equalTo(actualMessage.getSummary())));
assertThat("DETAIL_TEXT", is(equalTo(actualMessage.getDetail())));