在我们的项目中,我们正在使用Maven,Jersey和Mockito 2。具有PowerMockito 1.7.4依赖性的Mockito 2.7.5引起了一些问题:无法模拟本地范围变量的方法。这是我的示例代码:
import com.fasterxml.jackson.databind.ObjectMapper;
public Class Sample{
public String method1(String input){
ObjectMapper mapper = new ObjectMapper();
InputDO inputDO = mapper.readValue(input, InputDO.class);
}
}
Inside Test Class
@Test
public void testMethod(){
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
InputDO = inputDO = Mockito.mock(InputDO.class);
doReturn(inputDO).when(mapper).readValue(anyString(), eq(InputDO.class));
Sample s = Mockito.mock(Ssample.class);
s.method1(anyString());
assertNotNull(s);
}
mapper.raedValue()中的测试失败。请帮助我嘲笑上述步骤。
答案 0 :(得分:0)
测试失败,因为您在测试类中为ObjectMapper创建了一个模拟,但是在这里每次每次使用new关键字创建新的ObjectMapper时。
`class Test{
ObjectMapper ObjectMapperMock = new ObjectMapper();
ObjectMapper spymapper=spy(ObjectMapperMock);
doReturn(result).when(spymapper.readValue());
}
`
答案 1 :(得分:0)
确保您:
1)为测试类添加注释:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ObjectMapper.class)
2)将其添加为测试方法的第一行:
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);