我一直在尝试使用 mockito 和 junit 运行以下测试,但我不断收到“java.lang.NullPointerException:name must not be null” 谁能告诉我为什么会这样?
在调试时,我发现当测试在 isStopValid(String) 方法中执行以下语句时会抛出此异常:
FacilityValidationUtil facUtil = new FacilityValidationUtil();
@RunWith(MockitoJUnitRunner.class)
public class MyFormTest{
@InjectMocks MyForm form = new MyForm();
@Mock FacilityValidationUtil facUtil;
@Test
public void testIsStopValid() throws FinderException{
when(facUtil.isFacilityValid("")).thenReturn(false);
form.setOrigin("");
assertEquals(false, form.isStopValid(form.getOrigin()));
}
}
带有要测试的方法的类:
public class MyForm{
FacilityValidationUtil facUtil = new FacilityValidationUtil();
public boolean isStopValid(String stop){
try {
return facUtil.isFacilityValid(stop);
} catch (FinderException e) {
log.error("Error finding the stop. "+e.getCause());
return false;
}
}
}
public class FacilityValidationUtil{
private FacilityDAO facilityDao = new HibernateFacilityDAO();
public boolean isFacilityValid(String facility) throws FinderException{
boolean test;
FacilityImpl facilityImpl = facilityDao.findFacilityByNassCode(facility);
test = (facilityImpl==null)?false : true;
return test;
}
}
public class HibernateFacilityDAO extends HibernateAbstractDeltaDAO implements FacilityDAO {
public HibernateFacilityDAO() {
super(false);
}
}