首页 > 解决方案 > 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和测试所以我希望你能在这里帮助我。

谢谢!

标签: javaspringjunitmockito

解决方案


您需要为链式函数调用启用深度存根才能工作,

换个就行

@Mock
CsvMapper mapper;

@Mock(answer = RETURNS_DEEP_STUBS)
CsvMapper mapper;

推荐阅读