Java Mockito:如何在不模拟所有参数的情况下轻松存根方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2340801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:20:46  来源:igfitidea点击:

Mockito: How to easily stub a method without mocking all parameters

javaunit-testingmockingmockitostubbing

提问by Michael Bavin

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..);

采纳答案by SteveD

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 MyInterfaceand using JUnit 4):

我不太明白您在使用 Mockito 时遇到了什么问题。假设您创建了一个包含您的myMethod()方法的接口的模拟,然后您可以只验证您感兴趣的方法的参数。例如(假设接口被调用MyInterface并使用 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(), ...);
}

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.

您需要对 Mockito 方法进行静态导入才能使其工作。该any()匹配不关心验证时已通过什么样的价值。

You can't avoid passing something for every argument in your method (even if it's only NULL).

您无法避免为方法中的每个参数传递一些东西(即使它只是 NULL)。

回答by Aaron Digulla

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.

下次有机会时,针对项目提交错误,要求将参数移动到配置对象。

回答by Luis Ramirez-Monterosa

use mockito.any

使用 mockito.any

if myobj mymethod accepts string, string, bar for instance

如果 myobj mymethod 接受 string, string, bar 例如

to stub a call

存根呼叫

Mockito.when(myojb.myMethod(Mockito.anyString(),Mockito.anyString(),Mockito.any(Bar.class)))
    .thenReturn(amockedobject);

to verify SteveD gave the answer already

验证 SteveD 已经给出了答案

Mockito.verify(myojb).myMethod(
    Mockito.anyString(),Mockito.anyString(),Mockito.any(Bar.class)));