如何用Mokito模拟ObjectMapper?

时间:2019-04-01 15:47:36

标签: java

我无法使用Mokito来模拟ObjectMapper bean。

我的包含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{
...

}

我的测试课:

@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);

}

因此,当我调试此代码时,在ServiceParent中,objectMapper不为null,但readValue(...)返回null。

您对如何返回正确的模拟对象有想法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

@Mock创建一个新的模拟。等同于调用mock(SomeClass.class)

@MockBean创建一个类似@Mock的模拟,但还会使用该模拟替换具有相同类型的应用程序上下文中已存在的所有bean。因此,Autowire那个bean的任何代码都会得到模拟。

您需要使用@MockBean

相关问题