我是测试方面的新手。我在我的应用程序中使用了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。
答案 0 :(得分:0)
首先需要@Mock PrefixDao。 如果您使用的是Junit 5,则无需运行initMocks(this)。否则,您需要这样做:MockitoAnnotations.initMocks(this); 这样,mockito会将两个模拟Dao对象连接到您的服务。
我也看不到您为PatientDao嘲笑动作。 什么时候(PatientDao.create())。thenReturn(...);