本文介绍了调用给定的模拟void方法时执行自定义操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望Mockito在调用给定的void方法时执行自定义操作.
I would like to be able for Mockito to perform a custom action when a given void method is called.
说我有以下代码:
@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);
}
}
说我要向配置文件列表添加一个配置文件实例. Mockito可以做到吗?如果可以,怎么办?
Say I want to add a Profile instance to the profiles list. Can Mockito do that? If so how?
推荐答案
使用 Mockito.doAnswer .
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
// make the changes you need here
}})
.when(mock).someMethod();
这篇关于调用给定的模拟void方法时执行自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!