Mockito:如何在不模拟所有参数的情况下轻松存根方法 [英] Mockito: How to easily stub a method without mocking all parameters
问题描述
我有一个想存根的方法,但是它有很多参数. 我如何才能避免嘲笑所有参数,但仍存根该方法.
I have a method i'd like to stub but it has a lot of parameters. How can i avoid mocking all parameters but still stub the method.
例如:
//Method to stub
public void myMethod(Bar bar, Foo foo, FooBar fooBar, BarFoo barFoo, .....endless list of parameters..);
推荐答案
我不太了解您使用Mockito遇到的问题.假设您创建了一个包含myMethod()
方法的接口的模拟,然后可以仅验证您感兴趣的方法的参数.例如(假设该接口称为MyInterface
并使用JUnit 4): /p>
I don't quite follow what problem you're having using Mockito. Assuming you create a mock of the interface that contains your myMethod()
method, you can then verify only the parameters to the method that you are interested in. For example (assuming the interface is called MyInterface
and using JUnit 4):
@Test
public void test() {
MyInterface myInterface = mock(MyInterface.class);
FooBar expectedFooBar = new FooBar();
// other testing stuff
verify(myInterface).myMethod(any(), any(), eq(expectedFooBar), any(), ...);
}
您需要对Mockito方法进行静态导入才能使其正常工作. any()
匹配器不在乎在验证时传递了什么值.
You'll need to do a static import on the Mockito methods for this to work. The any()
matcher doesn't care what value has been passed when verifying.
您无法避免为方法中的每个参数传递某些内容(即使它只是NULL).
You can't avoid passing something for every argument in your method (even if it's only NULL).
这篇关于Mockito:如何在不模拟所有参数的情况下轻松存根方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!