Java 使用mockito时出现空指针异常

Java 使用mockito时出现空指针异常,java,spring-boot,nullpointerexception,mockito,Java,Spring Boot,Nullpointerexception,Mockito,我对Mockito完全陌生,已经花了几天时间在spring boot中编写我的web应用程序。这个应用程序运行得非常好,但我想学习mockito,并想测试我的一些类,包括controller,但是我发现这个测试部分非常令人沮丧,以至于我几乎要跳过这个测试部分。所以我会解释这个问题 Controller.java 现在,为了测试我的控制器,我编写了以下测试: WeatherRestControllerTest.java 但在运行测试的最后,我得到了以下异常: java.lang.NullPoint

我对Mockito完全陌生,已经花了几天时间在spring boot中编写我的web应用程序。这个应用程序运行得非常好,但我想学习mockito,并想测试我的一些类,包括controller,但是我发现这个测试部分非常令人沮丧,以至于我几乎要跳过这个测试部分。所以我会解释这个问题

Controller.java

现在,为了测试我的控制器,我编写了以下测试:

WeatherRestControllerTest.java

但在运行测试的最后,我得到了以下异常:

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的新实现。这是我根据注释中的输入所做的。

确保正确注入mockMvc

@AutoConfigureMockMvc
添加到测试中,使测试类声明如下所示:

@AutoConfigureMockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class WeatherRestControllerTest extends AbstractTestNGSpringContextTests
还要确保mockMvc是@Autowired

@Autowired
private MockMvc mockMVC;

通过这种方式,mockMvc被注入。

确保mockMvc被正确注入

@AutoConfigureMockMvc
添加到测试中,使测试类声明如下所示:

@AutoConfigureMockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class WeatherRestControllerTest extends AbstractTestNGSpringContextTests
还要确保mockMvc是@Autowired

@Autowired
private MockMvc mockMVC;

这样mockMvc就会被注入。

嗨,谢谢。是自动配置MockMVC为我工作。不过,我在上面的测试控制器中也做了一些小改动。现在我得到的唯一错误是
java.lang.AssertionError:Response内容预期:但是是:嗨,谢谢。是自动配置MockMVC为我工作。不过,我在上面的测试控制器中也做了一些小改动。现在,我得到的唯一错误是
java.lang.AssertionError:Response content expected:但是:
@Autowired
private MockMvc mockMVC;