简体   繁体   English

Mockito私有方法的参数

[英]Mockito argument to a private method

This is my sample service class: 这是我的示例服务类:

class Service {

    @Inject
    private TestDao dao;

    public void method() {
        //Other logic
        List<SomeClass> list = new ArrayList<SomeClass>();
        privateMethod(list);
        //Other logic
    }

    private void privateMethod(List<SomeClass> list) {
        dao.save(list);
    }
}

If I mock dao using Mockito, then how can I test the number of calls to dao.save method? 如果我使用Mockito模拟dao,那么如何测试对dao.save方法的调用次数? When I tried with verify, I have to give the list object. 当我尝试验证时,我必须提供列表对象。 But I am not seeing any way to get that object. 但是我没有看到任何获取该对象的方法。

Any thoughts? 有什么想法吗?

You can use the anyList() matcher if you don't care about exactly what list your method is being called with. 如果您不关心调用方法的确切列表,则可以使用anyList()匹配器。 For example, if you want to verify the save() method was called exactly thrice: 例如,如果要验证save()方法是否被正确调用三次:

verify(dao, times(3)).save(anyList())

If you want to make further assertions about what list save() was called with, use ArgumentCaptor 如果要进一步声明调用了哪个列表save() ,请使用ArgumentCaptor

An example usage of ArgumentCaptor : ArgumentCaptor用法示例:

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(dao, times(3)).save(argument.capture());
List secondValue = argument.getAllValues().get(1); // captured value when the method was called the second time

使用Matchers.anyList()调用verify:

verify(dao).save(Matchers.anyList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM