在调用给定的模拟 void 方法时执行自定义操作 [英] Performing a custom action when a given mocked void method is called

查看:16
本文介绍了在调用给定的模拟 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);
    }
}

假设我想将 Profile 实例添加到配置文件列表中.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 方法时执行自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆