【发布时间】:2015-09-30 11:47:15
【问题描述】:
我是测试方面的新手。我在我的应用程序中使用 Spring Mvc。我按照一些教程来编写控制器和服务测试用例。我在服务测试中遇到错误。请帮忙!
服务:
@Autowired
private PatientDao patientDao;
@Autowired
private PrefixDao prefixDao;
public Patient createPatient(Patient patient) throws Exception {
patient.setAgeorDob();
return createPatientInSync(patient);
}
private synchronized Patient createPatientInSync(Patient patient)
throws Exception {
try {
Prefix prefix = prefixDao.getPrefixForType(PrefixType.PATIENT);
patient.setPatientNo(prefix.getPrefixedNumber());
patientDao.createPatient(patient); //SAVE PATIENT
prefixDao.incrementPrefix(prefix);
} catch (ConstraintViolationException ex) {
throw new InternalErrorException("Please enter valid data", ex);
} catch (NullPointerException e) {
e.printStackTrace();
throw new InternalErrorException(
"Please create Prefix for Patient", e);
}
return patient;
}
服务测试用例:
@ContextConfiguration(locations = {
"classpath:/applicationContext-resources.xml",
"classpath:/applicationContext-service.xml",
"classpath:/applicationContext-dao.xml",
"classpath:/applicationContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class PatientServiceTest {
@Autowired
@Mock
private PatientDao patientDao;
@InjectMocks
private PatientServiceImpl patientService = new PatientServiceImpl();
private PrefixDao prefixDao;
@Before
public void doSetup() {
patientDao = mock(PatientDao.class);
prefixDao = mock(PrefixDao.class);
// Mockito.mock(PatientDao.class);
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSaveUser() throws Exception {
Patient mockPatient = new Patient();
mockPatient.setFirstName("Aravinth");
mockPatient.setSex(Gender.Male);
mockPatient.setAgeOrDob("24");
Prefix prefix = new Prefix();
prefix.setPrefixType(PrefixType.PATIENT);
prefix.setPrefix("Pat-");
prefix.setSequenceNo(23);
when(prefixDao.getPrefixForType(PrefixType.PATIENT)).thenReturn(prefix);
System.out.println(prefix.getSequenceNo());
mockPatient = patientService.createPatient(mockPatient);
assertEquals("Aravinth", mockPatient.getFirstName());
verify(patientDao, times(1)).createPatient(mockPatient);
}
}
验证时间工作正常。我在 assertEquals 中得到了 Nullpointer。
【问题讨论】:
-
签入你的patientDao实例,调用createPatient时,它返回null。
-
更新了我的 dao 代码.. @PupCode
-
你错了,你的 dao 是一个 Mock 对象,所以它不会运行你的实际代码......我在文档中看到这条指令放在注释之前:'MockitoAnnotations。 initMocks(this);'
-
嗨,小狗。同样的错误:-(分享任何示例链接
-
要熟悉 Mockito,请查看 this tutorial。通过仔细查看您的测试代码,我注意到两件事:1.您没有调用您可能想首先测试的
PatientSeriveImpl2.验证对createPatient的调用次数是没有用的,因为唯一的调用来自您的代码。
标签: java spring spring-mvc nullpointerexception mockito