Reputation: 163
I'm having trouble with mocking an ObjectMapper bean with mokito.
My class containing the ObjectMapper :
public class ServiceParent{
@Autowired
protected ObjectMapper objectMapper;
public void someMethod(){
...
Map<String, String> mapResponse = objectMapper.readValue("some json", new TypeReference<Map<String, String>>(){});
}
Other class extending previous one
public class ServiceChild extends ServiceParent{
...
}
My test class :
@SpringBootTest
public class TestService{
@Mock
ObjectMapper objectMapper;
@InjectMocks
ServiceChild serviceChild;
@Test
public void test(){
Map<String, String> mapResponse=new HashMap<String, String>();
mapResponse.put("access_token", "token_bouhon");
Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(mapResponse);
}
So when I debug this, in ServiceParent, objectMapper isn't null but readValue(...) return null.
Do you have an idea on how to return the correct mocked object?
Thanks
Upvotes: 2
Views: 8959
Reputation: 131
I faced the same NPE with the objectmapper. This issue is resolved after adding , my test class has class level annotation with
@RunWith(MockitoJUnitRunner.class)
and the fix
@Before
public void setupBefore() {
MockitoAnnotations.initMocks(this);
}
Upvotes: 1
Reputation: 21285
@Mock
creates a new mock. It's equivalent to calling mock(SomeClass.class)
@MockBean
creates a mock, like @Mock
, but also replaces any bean already in the application context with the same type with that mock. So any code which Autowire
s that bean will get the mock.
You need to use @MockBean
Upvotes: 0