模拟问题-尝试模拟外部API方法时出现Null指针异常

时间:2020-09-26 14:19:19

标签: java junit nullpointerexception mockito

我正在尝试测试课程:

public class WeatherProvider {

private OWM owm;

public WeatherProvider(OWM owm) {
    this.owm = owm;
}

public CurrentWeatherData getCurrentWeather(int cityId) throws APIException, UnknownHostException {

    CurrentWeatherData currentWeather = new CurrentWeatherData(owm.currentWeatherByCityId(cityId));

    return currentWeather;

}

public HourlyWeatherForecastData getHourlyWeather(int cityId) throws APIException, UnknownHostException {

    HourlyWeatherForecastData hourlyWeather = new HourlyWeatherForecastData(owm.hourlyWeatherForecastByCityId(cityId));

    return hourlyWeather;

}

}

OWM是一个外部API,因此我想对其进行模拟。我写了一个测试方法:

    @Test
void shouldReturnCurrentWeather() throws APIException, UnknownHostException {
    //given
    OWM owm = mock(OWM.class);
    WeatherProvider weatherProvider = new WeatherProvider(owm);
    int cityId = 123;
    CurrentWeather currentWeather = WeatherDataStub.getCurrentWeather();
    given(owm.currentWeatherByCityId(cityId)).willReturn(currentWeather);

    //when
    CurrentWeatherData currentWeatherData = weatherProvider.getCurrentWeather(cityId);

    //then

}

我在给定().willReturn()行中收到java.lang.NullPointerException,但我不知道为什么。我想测试owm.currentWeatherByCityId(cityId)成功返回CurrentWeather对象(在这种情况下是存根类)或引发异常的情况。 你能告诉我我做错了什么吗?

0 个答案:

没有答案