I am trying to test my method for getting back all entities that exist in my db. I am using JUnit and Mockito. I have no experience with testing so far and this is how far I've got: This is my method from the agency service to get back all entities, using the findAll() function of JpaRepository:
public List<AgencyDto> getAll() {
return repo.findAll().stream().map(agency -> mapper.mapToDto(agency)).collect(Collectors.toList());
}
@ExtendWith(MockitoExtension.class)
public class AgencyServiceTest {
@Mock
private AgencyRepository agencyRepository;
@InjectMocks
private AgencyService agencyService;
@Test
void getAgencies() {
List<AgencyDto> agencies = new ArrayList<AgencyDto>();
AgencyDto agency1 = new AgencyDto();
AgencyDto agency2 = new AgencyDto();
agency1.setName("agency");
agency1.setEmail("agency@yahoo.com");
agency2.setName("agencyy");
agency2.setEmail("agencyy@yahoo.com");
agencies.add(agency1);
agencies.add(agency2);
List<Agency> existingAgencies = new ArrayList<Agency>();
existingAgencies.add(mapper.mapToEntity(agency1));
existingAgencies.add(mapper.mapToEntity(agency2));
when(agencyRepository.findAll()).thenReturn(existingAgencies);
List<AgencyDto> result = agencyService.getAll();
assertEquals(agencies, result);
}
}
When running the test, the value for expected seems ok, but the value for actual is an empty array:
Expected :[com.project.DTOs.AgencyDto@245a26e1, com.project.DTOs.AgencyDto@4d63b624, com.project.DTOs.AgencyDto@466cf502]
Actual :[]
Is this not the right way to test get() methods? Am I doing something wrong when setting the actual result?
Issue is here
List<Agency> existingAgencies = new ArrayList<Agency>();
when(agencyRepository.findAll()).thenReturn(existingAgencies);
your mock returns an empty list, you need to add items to list
eg:
List<Agency> existingAgencies = new ArrayList<Agency>();
existingAgencies.add(yourDTOObject1);
existingAgencies.add(yourDTOObject2);
existingAgencies.add(yourDTOObject3);
when(agencyRepository.findAll()).thenReturn(existingAgencies);
List<Agency> result = agencyRepository.findAll();
assertEquals(agencies, result);
Also you miss to mock agencyService.getAll()
I think you need to do something like when(agencyService.getAll()).thenReturn(agencies);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.