How to return Page content in Spring Boot Unit test service layer? How to mock this data with some values and later on test it?
Service that needs to be tested:
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CampaignReadServiceImpl02 {
private final CampaignRepository campaignRepository;
public Page<Campaign> getAll(int page, int size) {
Pageable pageable = PageRequest.of(page, size);
Page<Campaign> pages = campaignRepository.findAll(pageable);
return pages;
}
}
The class that mocks data in Unit test
@Slf4j
@ExtendWith(MockitoExtension.class)
public class CampaignReadServiceTest {
@Mock
private CampaignRepository campaignRepository;
private CampaignReadServiceImpl02 campaignReadServiceImpl02;
@BeforeEach
public void beforeEach() {
campaignReadServiceImpl02 = new CampaignReadServiceImpl02(campaignRepository);
}
@Test
public void testGetAll02() {
log.info("Testing get all campaigns method");
//this need to have content data inside of page.getContent(), need to be added
Page<Campaign> page = Mockito.mock(Page.class);
Mockito.when(campaignRepository.findAll(Mockito.any(Pageable.class))).thenReturn(page);
Page<Campaign> result = campaignReadServiceImpl02.getAll(2, 2);
Assertions.assertNotNull(result);
Mockito.verify(campaignRepository, Mockito.times(1)).findAll(Mockito.any(Pageable.class));
Mockito.verifyNoMoreInteractions(campaignRepository);
}
}
How to mock Page<Campaign> page = Mockito.mock(Page.class);
to get result.getContent();
when Service repository is injected in Service..
I can't test result.getContent()
because I don't have data from repository, maube because I need to change mock Page<Campaign> page
with Page.class
to something else?
How to properly mock Page<Campaign> page = Mockito.mock(Page.class);
that will return some data later on in service: result.getContent().name(), etc..
CodePudding user response:
easiest way would be to create an object instead of mocking the class.
Page<TournamentEntity> tournamentEntitiesPage = new PageImpl<>(List.of(obj1, obj2), pageable, 0);