3

I already went through this question: How do I mock an autowired @Value field in Spring with Mockito?. How can we mock the following?

@Value("#{${patientTypes}}")
private Map<String, Integer> patientTypes;

So that we can access its value when doing mocking?

Georgii Lvov
  • 1,771
  • 1
  • 3
  • 17
PAA
  • 1
  • 46
  • 174
  • 282

1 Answers1

2

If you just want to mock your map and inject it in your class under test, you should just create a mock map and inject it via ReflectionTestUtils:

Class under test:

@Component
public class MyService {

    @Value("#{${patientTypes}}")
    private Map<String, Integer> patientTypes;

    public Integer getPatientTypeByKey(String key) {
        return patientTypes.get(key);
    }
}

For Mockito-test you can use just InjectMocks:

@ExtendWith(MockitoExtension.class)
public class SimpleTest {

    @InjectMocks
    private MyService underTest;

    @Mock
    private Map<String, Integer> mockMap;


    @Test
    public void test() {
        when(mockMap.get(anyString())).thenReturn(15);

        Integer result = underTest.getPatientTypeByKey("some key");

        assertEquals(15, result);
    }
}

For SpringBootTest ReflectionTestUtils can be used:

@SpringBootTest
public class SBTest {

    @Autowired
    private MyService underTest;

    @Mock
    private Map<String, Integer> mockMap;


    @Test
    public void test() {
        ReflectionTestUtils.setField(underTest, "patientTypes", mockMap);

        when(mockMap.get(anyString())).thenReturn(15);

        Integer result = underTest.getPatientTypeByKey("some key");

        assertEquals(15, result);
    }
}
Georgii Lvov
  • 1,771
  • 1
  • 3
  • 17
  • Hey Thanks, but this is not working for me `ReflectionTestUtils.setField(underTest, "patientTypes", mockMap);` – Jeff Cook Sep 09 '21 at 10:40