Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define mockito when with multiple any arguments

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?

like image 521
Shashi Ranjan Avatar asked Oct 03 '16 11:10

Shashi Ranjan


People also ask

What does Mockito EQ do?

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.

Is Mockito PowerMock Which is better?

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.

What is argument matcher in Mockito?

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.

What can I use instead of Mockito matchers?

Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.


1 Answers

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));
like image 52
Shashi Ranjan Avatar answered Sep 20 '22 01:09

Shashi Ranjan