How to mock Page with content data in Unit Test?
Asked Answered
E

1

6

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..

Endothecium answered 30/5, 2022 at 18:11 Comment(2)
Why don't you just instatiate the class : List<Campaign> campaignes= new ArrayList<>() Page<Campaign> pagedResponse = new PageImpl(companies) and then return it Mockito.when(campaignRepository.findAll(Mockito.any(Pageable.class))).thenReturn(pagedResponse) ?Haller
Your answer is working properly, it can be as accepted answer. But other one have more details to add on, like Pageable, total count, etc.. so I will accept other oneEndothecium
P
13

easiest way would be to create an object instead of mocking the class.

Page<TournamentEntity> tournamentEntitiesPage = new PageImpl<>(List.of(obj1, obj2), pageable, 0);
Paleethnology answered 30/5, 2022 at 23:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.