简体   繁体   English

使用Mockito时出现空指针异常

[英]null pointer exception while using mockito

I am totally new to Mockito and have already spent couple of days to write my web app in spring boot. 我对Mockito完全陌生,已经花了几天的时间在春季启动中编写我的Web应用程序。 The application runs perfectly fine but I want to learn mockito and want to test some of my class including controller, however I find this testing part so frustrating that I am almost on the verge of skipping this testing part. 该应用程序运行得很好,但是我想学习Mockito并想测试我的班级中的一些人,包括控制器,但是我发现这个测试部分令人沮丧,以至于我几乎快要跳过这个测试部分。 So I will explain the problem 所以我会解释这个问题

Controller.java 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";
        }

I want to test this controller which depends on one service which is: 我想测试此控制器,它取决于一项服务:

GetWeatherService.java 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;
    }
}

Now to test my controller i have written this test: 现在要测试我的控制器,我已经编写了此测试:

WeatherRestControllerTest.java 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"));
    }
}

But in the end on running the test I get this exception: 但是最后在运行测试时,我得到了这个异常:

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)

I get NullPointerException and I have no idea what is going wrong. 我收到NullPointerException,我不知道出了什么问题。 Why its throwing null. 为什么它抛出null。 I am trying from morning to understand syntax but I am getting nothing. 我从早上开始尝试去了解语法,但是什么也没得到。 I spent couple of time researching and changing syntax but getting same error. 我花了一些时间研究和更改语法,但遇到了同样的错误。 Why it is so complicated and I still don't understand what is the purpose of doing all this. 为什么它是如此复杂,我仍然不明白这样做的目的是什么。

EDIT: 编辑:

I now have new implementation for WeatherRestcontrollerTest.java above. 我现在上面有WeatherRestcontrollerTest.java的新实现。 This I did as per the inputs in comments. 我按照评论中的输入进行了此操作。

Ensure that the mockMvc gets injected properly. 确保正确注入了MockMvc。

Add @AutoConfigureMockMvc to your test so that your test class declaration looks like: @AutoConfigureMockMvc添加到您的测试中,以便您的测试类声明如下所示:

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

Also ensure that the mockMvc is @Autowired 还要确保嘲笑Mvc是@Autowired

@Autowired
private MockMvc mockMVC;

This way the mockMvc gets injected. 这样,mockMvc被注入。

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

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