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..);
@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.
To call a real method of a mock object in Mockito we use the thenCallRealMethod() method.
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).
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With