Spring Mvc服务测试(空指针)



我是新来的测试方。我在我的应用程序中使用Spring Mvc。我遵循了一些教程来编写控制器和服务测试用例。我在服务测试中遇到了错误。请帮忙!

Service:

@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);
    }
}

验证次数工作正常。asserequals中有空指针

需要先@Mock PrefixDao。如果您正在使用Junit 5,则不需要运行initMocks(this)。否则你需要这样做:MockitoAnnotations.initMocks(this);这样,mock将把两个mock Dao对象连接到您的服务。

我也没看到你嘲笑patientDao。当(patientDao.create ()) .thenReturn(…),

相关内容

  • 没有找到相关文章

最新更新