相关疑难解决方法(0)

如何使用Mockito模拟ObjectMapper.readValue()

我正在测试服务层,但不确定如何ObjectMapper().readValue在该类中进行模拟。我是新手mockito,可以弄清楚该怎么做。

以下是我的代码,

service.java

private configDetail fetchConfigDetail(String configId) throws IOException {
    final String response = restTemplate.getForObject(config.getUrl(), String.class);
    return new ObjectMapper().readValue(response, ConfigDetail.class);
}
Run Code Online (Sandbox Code Playgroud)

ServiceTest.java

@Test
public void testgetConfigDetailReturnsNull() throws Exception {

    restTemplate = Mockito.mock(restTemplate.class);
    Service service = new Service();
    Config config = Mockito.mock(Config.class);
    ObjectMapper objMapper = Mockito.mock(ObjectMapper.class);
            Mockito.doReturn("").when(restTemplate).getForObject(anyString(), eq(String.class));
    Mockito.doReturn(configDetail).when(objMapper).readValue(anyString(),eq(ConfigDetail.class));
    assertEquals(configDetail, service.getConfigDetail("1234"));
}
Run Code Online (Sandbox Code Playgroud)

运行此测试时,我得到以下结果,

com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
 at [Source: (String)""; line: 1, column: 0]
Run Code Online (Sandbox Code Playgroud)

在此处发布ServiceTest.Java

@RunWith(MockitoJUnitRunner.class)
public class ConfigServiceTest {

    @Mock
    private ConfigPersistenceService …
Run Code Online (Sandbox Code Playgroud)

junit mockito

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

junit ×1

mockito ×1