【问题标题】:null pointer exception while using mockito使用 mockito 时出现空指针异常
【发布时间】:2019-04-01 08:16:52
【问题描述】:

我对 Mockito 完全陌生,并且已经花了几天时间在 Spring Boot 中编写我的 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 并且我不知道出了什么问题。为什么它抛出空值。我从早上开始尝试理解语法,但我什么也没得到。我花了一些时间研究和更改语法,但得到了同样的错误。为什么它如此复杂,我仍然不明白做这一切的目的是什么。

编辑:

我现在有了上面 WeatherRestcontrollerTest.java 的新实现。这是我根据 cmets 中的输入进行的。

【问题讨论】:

    标签: java spring-boot nullpointerexception mockito


    【解决方案1】:

    确保 mockMvc 被正确注入。

    @AutoConfigureMockMvc 添加到您的测试中,以便您的测试类声明如下所示:

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

    还要确保 mockMvc 是 @Autowired

    @Autowired
    private MockMvc mockMVC;
    

    这样 mockMvc 就被注入了。

    【讨论】:

    • 您好,谢谢。对我有用的是 AutoConfigurationMockMvc。但是我也在上面的测试控制器中做了一些小的改动。现在我得到的唯一错误是java.lang.AssertionError: Response content expected:&lt;weather-history&gt; but was:&lt;&lt;!DOCTYPE html&gt; &lt;html&gt; 它似乎在控制器中返回html页面,但我希望它与字符串“weather-history”匹配
    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多