αƞjiβ
αƞjiβ

Reputation: 3246

Writing unit test for service function

I need some help to write test for the below method in the service layer. I am not sure how to mock those methods (in DAO as wells as in same service layer) in Mockito for this service. Before that I think I should mock whole for loop to avoid mocking of each of those methods. What is the proper way to write unit test for such method.

public List<CheckupHistoryDto> getCaseHistory(Individual patient, Individual doctor) {
    List<CheckupHistoryDto> checkupHistoryList = new ArrayList<ClaimHistoryDto>();
    List<CaseHistory> caseHistoryIds = caseDetailDao.fetchCaseIds(patient.getId(), doctor.getId());
    for(CaseHistory caseHistory : caseHistoryIds) {
        CheckupHistoryDto checkupHistoryDto = new CheckupHistoryDto();
        checkupHistoryDto.setDateOfCall(formatter.format(caseHistory.getCreateDate()));
        checkupHistoryDto.setPatientInfo(getPatientInfo(patient));
        checkupHistoryDto.setDoctorInfo(getDoctorInfo(doctor));
        checkupHistoryDto.setServiceProvided(caseDetailDao.fetchServiceHistory(caseHistory.getEventId()));
        checkupHistoryList.add(checkupHistoryDto);
    }
    return checkupHistoryList;
}

public Patient getPatientInfo(patient) {
    ...
}

public Doctor getDoctorInfo(doctor) {
    ...
}

And my test case

@Test
public void testHistoryList() {
  Individual patient = Mockito.mock(Individual.class);
  Individual doctor= Mockito.mock(Individual.class);
  List<CheckupHistoryDto> checkupHistory = caseService.getCaseHistory(patient, doctor);
  assertEquals(MOCK_LIST_SIZE, checkupHistory.size());
}

Upvotes: 0

Views: 61

Answers (1)

DwB
DwB

Reputation: 38300

Forget about "mocking the for loop", that makes no sense since it is part of the functionality you want to test; specifically, when you unit test class XQ, you never mock any portion of class XQ.

you need to mock the following:

  1. Individual.getId for the patient.
  2. Individual.getId for the doctor.
  3. whatever methods on the Individual class that are used by getPatientInfo method, for the patient.
  4. whatever methods on the Individual class that are used by the getDoctorInfo method, for the doctor.
  5. caseDetailDao.fetchCaseIDs
  6. caseDetailDao.fetchServiceHistory
  7. caseHistory.getCreateDate, if you return a list of mock objects from fetchCaseIds.
  8. caseHistory.getEventId, if you return a list of mock objects from fetchCaseIds.

You have some terrible code:

  1. caseHsitory.fetchCaseIds is clearly not returning caseIDs, it is returning case details.

Upvotes: 1

Related Questions