简体   繁体   English

Mockito 在使用 when 时抛出 NPE

[英]Mockito throws NPE when using when

I am currently stuck on a problem using Mockito and I can't find a solution.我目前在使用 Mockito 时遇到了一个问题,我找不到解决方案。

This is my method I want to test:这是我要测试的方法:

 @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) {

        }
    }
}

And this is my current test 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());

}

}

Now the problem is that whatever I do I always receive a NullPointerException for the现在的问题是,无论我做什么,我总是收到一个NullPointerException

when(mapper.readerFor(WeatherData.class).with(schema).readValues(stream)).thenReturn(iterator); when(mapper.readerFor(WeatherData.class).with(schema).readValues(stream)).thenReturn(iterator);

I am new to Mockito and testing so I hope you can help me here.我是Mockito和测试的Mockito ,所以我希望你能在这里帮助我。

Thanks!谢谢!

You need to enable deep stubbing for chained function calls to work,您需要为链式函数调用启用深度存根才能工作,

Just replace,换了就行

@Mock
CsvMapper mapper;

with

@Mock(answer = RETURNS_DEEP_STUBS)
CsvMapper mapper;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM