【发布时间】: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。
您知道如何返回正确的模拟对象吗?
谢谢
【问题讨论】:
-
将您的
@Mock ObjectMapper更改为@MockBean ObjectMapper -
另外,您的代码将 TypeReference 作为第二个参数传递,但您使用 Class 作为第二个参数进行模拟。
-
另外,既然你正在启动一个spring上下文,你应该
@Inject你的ServiceChild作为一个bean并删除@InjectMocks注释。 -
即使使用@MockBean objectMapper.readValues(...) 返回null。
标签: java