我想为支持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 ..
提前致谢
答案 0 :(得分: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);
}
}