JUnit – performs custom actions when the given mocked void method is called
•
Java
When a given void method is called, I want mockito to perform a custom operation
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); } }
Suppose I want to add a profile instance to the profile list Can mockito do it? If so
Solution
Use mockito doAnswer.
doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { // make the changes you need here }}) .when(mock).someMethod();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码