【问题标题】:How to mock ObjectMapper with mokito?如何用 mockito 模拟 ObjectMapper?
【发布时间】:2019-08-22 20:21:27
【问题描述】:

我在用 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。

您知道如何返回正确的模拟对象吗?

谢谢

【问题讨论】:

  • 这将对您有所帮助:stackoverflow.com/questions/19299513/…
  • 将您的 @Mock ObjectMapper 更改为 @MockBean ObjectMapper
  • 另外,您的代码将 TypeReference 作为第二个参数传递,但您使用 Class 作为第二个参数进行模拟。
  • 另外,既然你正在启动一个spring上下文,你应该@Inject你的ServiceChild作为一个bean并删除@InjectMocks注释。
  • 即使使用@MockBean objectMapper.readValues(...) 返回null。

标签: java


【解决方案1】:

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

@MockBean 创建一个模拟,如@Mock,但也将应用程序上下文中已存在的任何 bean 替换为与该模拟相同的类型。所以任何Autowires bean 的代码都会得到模拟。

你需要使用@MockBean

【讨论】:

  • 即使使用@MockBean 它也会返回null。另外,我为什么要使用它而不是@Mock?我的观点只是嘲笑这个特定的 bean
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多