java - Mockito 在使用时抛出 NPE
问题描述
我目前在使用 Mockito 时遇到问题,找不到解决方案。
这是我要测试的方法:
@Override
public WeatherData getData(String wmoId, String location) {
// Creates a specific csv mapper
CsvSchema schema = factory.createEmptySchemaWithHeaderAndCommaSeperator();
CsvMapper mapper = factory.createCsvMapper();
MappingIterator<WeatherData> order = factory.createNullMappingIterator();
try {
order = mapper.readerFor(WeatherData.class).with(schema)
.readValues(factory.createBufferedInputStream(factory.createWmoUrl(wmoId)));
WeatherData current = order.readAll().get(2);
current.setStationName(location);
return current;
} catch (Exception e) {
return createErrorWeatherData(location);
} finally {
try {
order.close();
} catch (IOException e) {
}
}
}
这是我目前的测试课
@ExtendWith(MockitoExtension.class)
class WeatherDataServiceImplTest {
@InjectMocks
WeatherDataServiceImpl service;
@Mock
Factory factory;
@Mock
CsvSchema schema;
@Mock
CsvMapper mapper;
@Mock
BufferedInputStream stream;
@Mock
MappingIterator<Object> iterator;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void testGetDataWithInvalidStreamReturnsErrorObject() throws Exception {
lenient().when(factory.createCsvMapper()).thenReturn(mapper);
lenient().when(factory.createEmptySchemaWithHeaderAndCommaSeperator()).thenReturn(schema);
lenient().when(factory.createNullMappingIterator()).thenReturn(null);
when(mapper.readerFor(WeatherData.class).with(schema).readValues(stream)).thenReturn(iterator);
WeatherData data = service.getData("id", "location");
// assertEquals("location", data.getStationName());
}
}
现在的问题是,无论我做什么,我总是会收到NullPointerException
一个
when(mapper.readerFor(WeatherData.class).with(schema).readValues(stream)).thenReturn(iterator);
我是新手Mockito
和测试所以我希望你能在这里帮助我。
谢谢!
解决方案
您需要为链式函数调用启用深度存根才能工作,
换个就行
@Mock
CsvMapper mapper;
和
@Mock(answer = RETURNS_DEEP_STUBS)
CsvMapper mapper;
推荐阅读
- javascript - Redux-Saga:UI 阻塞,直到 api 调用返回大块 api 请求。我们如何在不阻塞 ui 的情况下实现这一点?
- sql-server - 如何在 SQL Server 中添加列的值,但只能在艺术家相同的地方添加?
- c++ - 检索 c++11 枚举的基础类型
- r - R:根据部分匹配字符将列添加到数据框
- android - Recyclerview 项目 onClick 在更新时不起作用
- java - HTTP 状态 500 – Servlet-JSP 中的内部服务器错误
- swift - 如何从本地存储加载数据...我尝试了很多东西但没有任何效果
- c# - Asp.Net Core - 在响应返回后需要服务时如何处理服务生命周期?
- python - 在dict中查找基于键的值长度
- r - 为什么我的前导函数会生成 NA 值?