I would like to be able for Mockito to perform a custom action when a given void method is called.
Say I have the following code:
@Autowired private ProfileService profileService; @Autowired private ProfileDao profileDao; private List<Profile> profiles; @Before public void setup() { Mockito.when(profileDao.findAll()).thenReturn(profiles); Mockito.when(profileDao.persist(any(Profile.class))).thenAddProfileToAboveList... } @Configuration public static class testConfiguration { @Bean public ProfileDao ProfileDao() { return mock(ProfileDao.class); } }
Say I want to add a Profile instance to the profiles list. Can Mockito do that? If so how?
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.
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
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.
mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter. mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure.
Use Mockito.doAnswer.
doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { // make the changes you need here }}) .when(mock).someMethod();
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