如何解决模拟文件返回 NPE
试图模拟代码但获得 NPE。我正在使用 Powermockito v2。我还在学习Mockito,如果发现测试方法有错误,请指正。
这是测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest(CellConfig.class)
public class CellConfigTest {
@Test
public void testCellsMap() throws Exception {
Map<String,String> cellMap = new HashMap<>();
cellMap.put("key1","value1");
CellConfig cellConfigSpy = PowerMockito.spy(new CellConfig());
PowerMockito.when(cellConfigSpy,PowerMockito.method(cellConfig.class,"cellMap"))
.withArguments(Mockito.any(String.class),Mockito.anyList()).thenReturn(cellMap);
Paths paths = PowerMockito.mock(Paths.class);
Path path = PowerMockito.mock(Path.class);
Stream<String> mockStream = PowerMockito.mock(Stream.class);
Files filesMock = PowerMockito.mock(Files.class);
PowerMockito.when(filesMock.lines(path)).thenReturn(mockStream); // NPE
cellConfigSpy.publicMethod();
}
}
测试方法如下:
public Map getCells() {
//does few things
Map m = getCellsInfo(dir,cellList);
}
private Map getCellsInfo(String dir,List cList) {
File[] files = new File(dir).listFiles();
if (null == files) {
return Collections.emptyMap();
}
return cellMap(dir,cList)
}
private Map<String,String> cellMap(String cellDir,List<String> cellKeys) {
Map<String,String> cellMap = new HashMap<>();
if (null != cellKeys) {
cellKeys.forEach(key -> {
try (Stream<String> stream = Files.lines(Paths.get(cellDir + key))) {
stream.forEach(value -> cellMap.put(key,value));
} catch (IOException e) {
}
});
}
return cellMap;
}
模拟此代码的建议方法是什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。