Java 模拟问题-尝试模拟外部API方法时出现空指针异常
我正在尝试测试这个类:Java 模拟问题-尝试模拟外部API方法时出现空指针异常,java,junit,nullpointerexception,mockito,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 current
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
}
我在gived().willReturn()行中得到一个java.lang.NullPointerException,我不知道为什么。我想测试owm.currentWeatherByCityId(cityId)成功返回CurrentWeather对象(在本例中是存根类)或抛出异常时的情况。
你能给我解释一下我做错了什么吗?当你把断点放在有问题的行上并在调试中运行测试时,哪个变量是
null
owm
,currentWeather
(但这应该不是问题),或者可能是给定的表达式(owm.currentWeatherByCityId(cityId))
?currentWeather不为空。owm是“针对owm的Mock,hashCode…”,但对象的每个字段都是null(比如apiKey、language、baseURL等等)。当我将给定()表达式添加到监视列表时,它说“方法抛出了NullPointerExcepion”。我不知道如何解释它。我认为它是给定的()表达式,它是空的。看起来像是Mockito的某种错误配置。测试类中是否有@RunWith(MockitoJUnitRunner.class)
?如果将mockito的any()
、anyInt()
或eq(cityId)
而不是cityId
放在有问题的行中,它是否解决了NPE?