Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 672
Naanavanalla Avatar asked Jul 19 '17 11:07

Naanavanalla


People also ask

Can we mock an interface?

mock() The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.

What is mocking a method?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.

How do you mock method which returns void?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.


1 Answers

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); 
like image 158
Darshan Mehta Avatar answered Sep 24 '22 05:09

Darshan Mehta