我目前在使用 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) {
}
}
}
这是我当前的测试类(class)
@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
和测试的新手,所以我希望你能在这里帮助我。
谢谢!
最佳答案
您需要启用deep stubbing为了使链式函数调用正常工作,
直接替换
@Mock
CsvMapper mapper;
与
@Mock(answer = RETURNS_DEEP_STUBS)
CsvMapper mapper;
关于java - Mockito 使用时抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59500046/