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
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With