简体   繁体   中英

Using Mockito, how do I check for a key-value pair of a map within when clause

Referred to: SimilarQuestion1 , SimilarQuestion2 , SimilarQuestion3

From the reference, I was able to derive a partial solution as follows, though it is syntactically incorrect. How do I modify this to correctly search for certain keys with null values.

when(storedProc.execute(anyMapOf(String.class, Object.class).allOf(hasEntry("firstIdentifier", null), hasEntry("secondIdentifier", null))))
   .thenThrow(new Exception(EXCEPTION_NO_IDENTIFIER));

Any help will be appreciated.

In your case you can use eq with provided filled map:

    when(storedProc.execute(Mockito.eq(givenIncorrectMap)))
            .thenThrow(new Exception(EXCEPTION_NO_IDENTIFIER));

Full example:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;

import static org.mockito.Mockito.when;

public class QuestionTest {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    interface A {
        String execute(Map<String, Object> map);
    }

    @Test
    public void test() {
        // Given a map with missed identifiers.
        final Map<String, Object> givenIncorrectMap = new HashMap<>();
        givenIncorrectMap.put("firstIdentifier", null);
        givenIncorrectMap.put("secondIdentifier", null);

        // Given a mocked service
        final A mockedA = Mockito.mock(A.class);

        // which throws an exception exactly for the given map.
        when(mockedA.execute(Mockito.eq(givenIncorrectMap)))
                .thenThrow(new IllegalArgumentException("1"));


        // Now 2 test cases to compare behaviour:


        // When execute with correct map no exception is expected
        mockedA.execute(Collections.singletonMap("firstIdentifier", "any correct value"));

        // When execute with incorrect map the IllegalArgumentException is expected
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("1");

        mockedA.execute(givenIncorrectMap);
    }
}

The problem is that anyMap returns a Map and not a Matcher. So replace your anyMap(...)... by:

Mockito.argThat(CoreMatchers.allOf(
  hasEntry("firstIdentifier", null), 
  hasEntry("secondIdentifier", null)))

Maybe you have to add some type variable hints, such that it compiles.

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