28

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 Answers 3

30

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

2
  • 4
    I guess he really wants to call myMethod(), so he needs to pass all those parameters every time which bloats the test. Feb 26, 2010 at 10:42
  • I'm testing a controller and i'm stubbing my service method. the service is mocked. I guess the any() should work. Thanks Feb 26, 2010 at 10:54
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)));
3

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.

4
  • 5
    True - too many parameters on a method signature is a bad code 'smell'.
    – SteveD
    Feb 26, 2010 at 10:27
  • I'm having 5 parameters, and yes they are needed:) It's a service method i'm trying to stub. I only wanted to be theoretical for methods where you don't really want to stub the parameters Feb 26, 2010 at 10:51
  • The problem with "a million" arguments seems to be a very common problem with many SOAP services. #fail
    – Kimble
    Aug 26, 2011 at 8:27
  • 2
    @Michael Bavon: The question isn't "Are they needed" but the fact that the poor human brain gets easily confused when it has to get five parameters right. Especially when they are all strings... :-) Google for "builder pattern" for a nice and simple solution. Aug 29, 2011 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.