簡體   English   中英

使用Mockito時出現空指針異常

[英]null pointer exception while using mockito

我對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的新實現。 我按照評論中的輸入進行了此操作。

確保正確注入了MockMvc。

@AutoConfigureMockMvc添加到您的測試中,以便您的測試類聲明如下所示:

@AutoConfigureMockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class WeatherRestControllerTest extends AbstractTestNGSpringContextTests

還要確保嘲笑Mvc是@Autowired

@Autowired
private MockMvc mockMVC;

這樣,mockMvc被注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM