使用Mockito2.7模拟局部范围对象的方法



我们在项目中使用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((中失败。请帮助我模拟以上步骤。

确保:

1(用注释测试类

@RunWith(PowerMockRunner.class)
@PrepareForTest(ObjectMapper.class)

2(将其作为测试方法的第一行:

ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);

测试失败,因为您在测试类中为ObjectMapper创建了一个Mock,但在这里每次使用新关键字创建新的ObjectMapper。所以会更好

`class Test{
ObjectMapper ObjectMapperMock = new ObjectMapper();
ObjectMapper spymapper=spy(ObjectMapperMock);
doReturn(result).when(spymapper.readValue());
}

`

最新更新