Mockito: How to easily stub a method without mocki

2019-03-23 04:31发布

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

3条回答
迷人小祖宗
2楼-- · 2019-03-23 04:54

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.

查看更多
Root(大扎)
3楼-- · 2019-03-23 05:13

use mockito.any

if myobj mymethod accepts string, string, bar for instance

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

Mockito.verify(myojb).myMethod(
    Mockito.anyString(),Mockito.anyString(),Mockito.any(Bar.class)));
查看更多
劳资没心,怎么记你
4楼-- · 2019-03-23 05:14

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(), ...);
}

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

查看更多
登录 后发表回答