lukaszFD
lukaszFD

Reputation: 99

How to mock a custom Map?

Below should return a mock Map and when I want to do Mockito.When for a custom Map an error is returned. How to do Mockito.When so that there is no error and correct Map is returned ?

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
String cannot be returned by getTestMap2()
getTestMap2() should return Map

Test class

@Mock
private TestConfig testConfig;
@Test
public void testMapFunct()  
{
    Map<String, String> myMap = new HashMap<String, String>() {{put("a", "b");}};

    when(testConfig.testMap2().get("test1")).thenReturn( myMap );
}

TestConfig.java

@Configuration
@ConfigurationProperties(prefix = "map")
@Data
public class TestConfig {
    private Map<String, Long> testMap1;
    private Map<String, String> testMap2;
}

app.yml

map:
  testMap1:
    test1: '1'
    test1: '2'
    test1: '3'
  testMap2:
   test1: "net1"
   test2: "net2"
   test3: "net3"

Upvotes: 1

Views: 150

Answers (1)

Rob Spoor
Rob Spoor

Reputation: 9135

You should mock the result of testConfig.testMap2(), not one of its method calls:

// without .get("test1")
when(testConfig.testMap2()).thenReturn(myMap);

Upvotes: 1

Related Questions