Reputation: 1263
I want to pass a specific map
as argument in when
statement.
Map<String, String> someSpecificMap = new HashMap<>;
@Before
public void setUp() {
someSpecificMap.put("key", "value");
when(mockedObject.get(new MapParametersMatcher()).thenReturn(1);
}
@Test
public void test() {
//some code that invokes mocked object and passes into it map with ("key", "value")
}
class MapParametersMatcher extends ArgumentMatcher {
@Override
public boolean matches(Object argument) {
if (argument instanceof Map) {
Map<String, String> params = (Map<String, String>) argument;
if (!params.get("key").equals("value")) {
return false;
}
}
return true;
}
}
But matches() method isn't invoked. And test failed.
Upvotes: 0
Views: 8355
Reputation: 8932
If you want to check for a specific object that where .equal
returns true, you don't need to use an argument matcher, simply pass it as an argument:
@Before
public void setUp() {
Map<String, String> = new HashMap<>();
someSpecificMap.put("key", "value");
when(mockedObject.get(someSpecificMap).thenReturn(1);
}
The mocked return value of 1 will be returned if you pass a map that is equal to someSpecificMap, i.e. a map with one element "key": "value"
If you want to check if the map has a specific key, then I would suggest that you use the Hamcrest hasEntry matcher:
import static org.hamcrest.Matchers.hasEntry;
import static org.mockito.Matchers.argThat;
@Before
public void setUp() {
when(mockedObject.get((Map<String, String>) argThat(hasEntry("key", "value"))))
.thenReturn(1);
}
This mock setup returns 1 for all invocations of mockedObject.get
that get passed a map with the key "key": "value", other keys may be present or not.
Upvotes: 1