Mocking a method which returns Page interface

Naanavanalla picture Naanavanalla · Jul 19, 2017 · Viewed 18.8k times · Source

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

Answer

Darshan Mehta picture Darshan Mehta · Jul 19, 2017

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);