Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a custom action when a given mocked void method is called

Tags:

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?

like image 301
balteo Avatar asked Jun 13 '13 13:06

balteo


People also ask

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.

Which method call can be used to setup a mock object method?

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.

What is method mocking?

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.

What is mock method in Mockito?

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.


1 Answers

Use Mockito.doAnswer.

doAnswer(new Answer() {    public Object answer(InvocationOnMock invocation) {        // make the changes you need here    }})  .when(mock).someMethod(); 
like image 156
John B Avatar answered Oct 25 '22 15:10

John B