我对Mockito完全陌生,已经花了几天时间在春季启动中编写我的Web应用程序。该应用程序运行得很好,但是我想学习Mockito并想测试我的班级中的一些人,包括控制器,但是我发现这个测试部分令人沮丧,以至于我几乎快要跳过这个测试部分。所以我会解释这个问题
Controller.java
@GetMapping("/checkWeather")
public String checkWeather(@RequestParam(name="city", required=true, defaultValue="Oops! you typed wrong url!")
String city, Map<String,Object> map, Model model)
throws IOException,HttpClientErrorException.NotFound {
try{
Weather result = getWeatherService.getNewWeatherObject(city);
map.put("weatherList",crudService.getAllWeatherList());
}catch (HttpClientErrorException e){
LOGGER.info("Typed City cannot be found, please type name correctly! Aborting program..");
return "notfound";
}
return "weather-history";
}
我想测试该控制器,该控制器取决于一项服务:
GetWeatherService.java
@Service
public class GetWeatherService {
@Autowired
private ReadJsonObjectService readJsonObjectService;
public Weather getNewWeatherObject(String city) throws IOException {
String appid = "47c473417a4db382820a8d058f2db194";
String weatherUrl = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&APPID="+appid+"&units=metric";
RestTemplate restTemplate = new RestTemplate();
String restTemplateQuery = restTemplate.getForObject(weatherUrl,String.class);
Weather weather = readJsonObjectService.setWeatherModel(restTemplateQuery);
return weather;
}
}
现在要测试我的控制器,我已经编写了此测试:
WeatherRestControllerTest.java
@AutoConfigureMockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class WeatherRestControllerTest extends AbstractTestNGSpringContextTests {
private Weather weather;
@Autowired
private MockMvc mockMVC;
@InjectMocks
private WeatherRestController weatherRestController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCheckWeather() throws Exception {
GetWeatherService getWeatherService = Mockito.mock(GetWeatherService.class);
Mockito.when(getWeatherService.getNewWeatherObject("Munich")).thenReturn(new Weather());
mockMVC.perform(MockMvcRequestBuilders.get("/checkWeather?city=Munich")).
andExpect(MockMvcResultMatchers.status().isOk()).
andExpect(MockMvcResultMatchers.content().string("weather-history"));
}
}
但是最后运行测试却得到了这个异常:
java.lang.NullPointerException
at com.weatherapi.test.weather_api.rest.WeatherRestControllerTest.getWeatherRest(WeatherRestControllerTest.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
我收到NullPointerException,我不知道出了什么问题。为什么其抛出null。我从早上开始尝试去了解语法,但是什么也没得到。我花了一些时间研究和更改语法,但遇到了同样的错误。为什么它是如此复杂,我仍然不明白这样做的目的是什么。
编辑:
我现在上面有WeatherRestcontrollerTest.java的新实现。我按照评论中的输入进行了此操作。