简体   繁体   中英

Mockito: how to pass specific map as argument in when statement?

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.

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM