【问题标题】:jUnits for backing bean with contructer使用构造函数支持 bean 的 jUnits
【发布时间】:2013-05-29 08:38:10
【问题描述】:

我想为支持 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..

提前致谢

【问题讨论】:

    标签: unit-testing junit junit4 jsf-1.2


    【解决方案1】:

    您需要 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);
      }
    
    }
    

    【讨论】:

    • 能否请您建议我如何为上述方法编写 jUnit 测试用例,以便我有一个想法……我对 jUnit 不太了解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多