0

我想为支持 bean 中的方法编写 jUnit 测试用例,但问题是 bean 的构造函数对“facesContext”方法有一些调用。电话是这样的

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().
  put(
    BEAN_NAME,
    BEAN_OBJECT
  );

如果我编写任何测试用例,它会抛出“NullPointerException”。我知道这是因为 facesContext 没有初始化。

例如,如果我有这样的方法

public String disableFields() throws ApplicationException
{
  logger.info(empId);
  logger.info(relationShip.getRelationshipName());
  if(relationShip.getRelationshipName().equalsIgnoreCase("select"))
  {
    errorMessage="Please select relationship";
    Utils.addMessage(errorMessage, FacesMessage.SEVERITY_ERROR);
    return null;
  }


  showEmpName=true;// boolean value
  return null;
}

如果可能的话,请建议我使用 jUnit 测试用例的代码......

请建议为这些类型的方法编写 jUnits 测试用例的任何方法..我正在使用 jsf 1.2..

提前致谢

4

1 回答 1

0

您需要 PowerMockito 的功能来模拟静态方法,如下所述:https ://code.google.com/p/powermock/wiki/MockStatic

这是一个工作示例:

import org.hamcrest.core.IsEqual;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import javax.faces.application.FacesMessage;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class AppTest {

  public static final String PLEASE_SELECT_RELATIONSHIP = "Please select relationship";

  @Test
  public void testDisableFields() throws Exception {

    PowerMockito.mockStatic(Utils.class);

    Relationship relationShip = Mockito.mock(Relationship.class);
    App app = new App(1, relationShip);

    Mockito.when(relationShip.getRelationshipName()).thenReturn("SeLeCt");


    app.disableFields();

    Assert.assertThat(app.getErrorMessage(), IsEqual.equalTo(PLEASE_SELECT_RELATIONSHIP));

    PowerMockito.verifyStatic(Mockito.times(1));
    Utils.addMessage(PLEASE_SELECT_RELATIONSHIP, FacesMessage.SEVERITY_ERROR);
  }

}
于 2013-05-29T08:45:30.173 回答