Mockito:如何在不模拟所有参数的情况下轻松存根方法
我有一个想要存根的方法,但它有很多参数。 我怎样才能避免模拟所有参数但仍然存根该方法。
前任:
//Method to stub
public void myMethod(Bar bar, Foo foo, FooBar fooBar, BarFoo barFoo, .....endless list of 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.
Ex:
//Method to stub
public void myMethod(Bar bar, Foo foo, FooBar fooBar, BarFoo barFoo, .....endless list of parameters..);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不太明白你在使用 Mockito 时遇到了什么问题。假设您创建了包含
myMethod()
方法的接口模拟,则您可以仅验证您感兴趣的方法的参数。例如(假设该接口名为MyInterface
并使用 JUnit 4):您需要对 Mockito 方法进行静态导入才能使其工作。
any()
匹配器并不关心验证时传递了什么值。您无法避免为方法中的每个参数传递一些内容(即使它只是 NULL)。
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 calledMyInterface
and using JUnit 4):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.You can't avoid passing something for every argument in your method (even if it's only NULL).
使用mockito.any
例如,如果 myobj mymethod 接受 string、string、bar,则
来存根调用
以验证 SteveD 是否已给出答案
use mockito.any
if myobj mymethod accepts string, string, bar for instance
to stub a call
to verify SteveD gave the answer already
创建一个包装类,它调用真正的方法并填充除您提供的参数之外的所有参数(也称为“委托”)。
并在下一次机会时,针对项目提交错误,要求将参数移动到配置对象。
Create a wrapper class which calls the real method and fills in all the arguments but the ones you supply (a.k.a "delegation").
And at the next opportunity, file a bug against the project asking to move the parameters to a config object.