I am trying to define when
mockito method with multiple any
arguments:
TestBedDaoClient testBedDaoClient = mock(TestBedDaoClient.class);
when(testBedDaoClient.addTestBed(anyString(), anyString(), any(VCloudConfiguration.class))).thenReturn(testBedPojoMockData);
In target test class:
TestBedPojo addedTestBedPojo = testBedDaoClient.addTestBed(testBedName, testBedDescription, vCloudConfiguration);
In DAO client:
public TestBedPojo addTestBed(String testBedName, String testBedDescription, VCloudConfiguration vCloudConfiguration){
return testBedPojo;
}
I wanted to define when
in such a way that it returns testBedPojoMockData
with any values of arguments. But I am getting error: Argument(s) are different!
I even tried:
when(testBedDaoClient.addTestBed("test", "test", any(VCloudConfiguration.class))).thenReturn(testBedPojoMockData);
when(testBedDaoClient.addTestBed(any(), any(), any())).thenReturn(testBedPojoMockData);
But no luck. How I can define this when
so that it returns the mock data on any call?
By default, Mockito verifies argument values by using the equals() method, which corresponds to == in Kotlin. However, once argument matchers like any() are used, then the eq argument matcher must be used for literal values. In MockK, eq is always used as the default argument matcher.
While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.
Argument matchers are mainly used for performing flexible verification and stubbing in Mockito. It extends ArgumentMatchers class to access all the matcher functions. Mockito uses equal() as a legacy method for verification and matching of argument values.
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.
The correct combination of when
and verify
should be used. It's failing on any other combination of argument in addTestBed
method.
when(testBedDaoClient.addTestBed(anyString(), anyString(), any(VCloudConfiguration.class))).thenReturn(testBedPojoMockData);
//calling target method
verify(testBedDaoClient, times(1)).addTestBed(anyString(), anyString(), any(VCloudConfiguration.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