Search code examples
javajunitmockitopowermockito

Mocking a method which returns Page interface


I have a method which I need to write unit test case. The method returns a Page type.

How can I mock this method?

Method:

public Page<Company> findAllCompany( final Pageable pageable )
{
    return companyRepository.findAllByIsActiveTrue(pageable);
}

Thanks for the help


Solution

  • You can use a Mock reponse or an actual response and then use when, e.g.:

    Page<Company> companies = Mockito.mock(Page.class);
    Mockito.when(companyRepository.findAllByIsActiveTrue(pageable)).thenReturn(companies);
    

    Or, just instantiate the class:

    List<Company> companies = new ArrayList<>();
    Page<Company> pagedResponse = new PageImpl(companies);
    Mockito.when(companyRepository.findAllByIsActiveTrue(pagedResponse)).thenReturn(pagedResponse);