36

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

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Naanavanalla
  • 1,412
  • 2
  • 27
  • 52

1 Answers1

74

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);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • 2
    What is `pageable` in this context? The repository method findAllCompany has access to it, but the test don't. I would want to mock that `Pageable pageable` parameter too, along with `Page` return type. – Dalibor Filus Jul 10 '18 at 11:51
  • @DarshanMehta - Could you pls guide me here: https://stackoverflow.com/questions/56135373/optional-cannot-be-returned-by-stream-in-mockito-test-classes ? – PAA May 14 '19 at 19:12
  • 1
    will it give a page where nothing is there? then why to use? – Satish Patro Jul 25 '19 at 14:32