Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: How to easily stub a method without mocking all 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..); 
like image 744
Michael Bavin Avatar asked Feb 26 '10 10:02

Michael Bavin


People also ask

What is difference between @mock and @injectmock?

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

How do you mock another method that is being tested in the same 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.

What does lenient do in Mockito?

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.

How do you call a real method on a mock object?

To call a real method of a mock object in Mockito we use the thenCallRealMethod() method.


2 Answers

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

like image 147
SteveD Avatar answered Sep 28 '22 18:09

SteveD


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))); 
like image 22
Luis Ramirez-Monterosa Avatar answered Sep 28 '22 18:09

Luis Ramirez-Monterosa