测试Controller时出现java.lang.NullPointerException的原因排查
Spring Controller测试NullPointerException排查
问题现象
测试Spring Controller时抛出java.lang.NullPointerException,错误信息:Cannot invoke "ru.se_nata.ati.service.AtiServiceImpl.findAllActHasForm()" because "this.atiServiceImpl" is null
测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestContext.class,}) @WebAppConfiguration public class AtiActHasFormControllerTest { MockMvc mvc; @Autowired private AtiServiceImpl atiServiceImpl; @Autowired private WebApplicationContext webAppContext; @Before public void setup() { mvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); } private List<ActHasForm> getActHasForm() { RegulatoryAct newoneRegulatoryAct = new RegulatoryAct(1, "4927-У", new Date(2018 - 01 - 10), "О перечне, формах и порядке составления и представления форм", "указание регулирует составление отчетности"); RegulatoryForm newoneRegulatoryForm = new RegulatoryForm(1, "0403202", "Сведения об оценке выполнения операторами", "форма ДИБ (нерегулярная)", new Date(2019 - 03 - 30), new Date(2022 - 12 - 12), new Date(2012 - 01 - 13)); RegulatoryAct newtwoRegulatoryAct = new RegulatoryAct(1, "4847-У", new Date(2018 - 01 - 11), "О ВНЕСЕНИИ ИЗМЕНЕНИЙ В УКАЗАНИЕ ", "регулирует составления отчетности"); RegulatoryForm newtwoRegulatoryForm = new RegulatoryForm(1, "0403582", "Сведения о событиях,", "Форма ДИБ (Квартальна", new Date(2019 - 03 - 23), new Date(2023 - 01 - 12), new Date(2022 - 12 - 12)); ActHasForm oneActHasForm = new ActHasForm(1, newoneRegulatoryAct, newoneRegulatoryForm, "Новая редакция формы"); ActHasForm twoActHasForm = new ActHasForm(1, newtwoRegulatoryAct, newtwoRegulatoryForm, "Новая редакция формы"); return List.of(oneActHasForm, twoActHasForm); } @Test void findAllActHasForm() throws Exception { Mockito.when(this.atiServiceImpl.findAllActHasForm()).thenReturn(getActHasForm()); mvc.perform(get("/acthasform/")) .andExpect(status().isOk()) .andExpect(view().name("acthasform/list")) .andExpect(forwardedUrl("/resuorses/templates/acthasform/list.html")) .andExpect(model().attribute("acthasform", hasSize(2))) .andExpect(model().attribute("acthasform", hasItem( allOf( hasProperty("id", is(1L)), hasProperty("actId", is("4927-У")), hasProperty("formId", is("0403202")) ) ))) .andExpect(model().attribute("todos", hasItem( allOf( hasProperty("id", is(2L)), hasProperty("actId", is("4847-У")), hasProperty("formId", is("0403582")) ) ))); verify(atiServiceImpl, times(1)).findAllActHasForm(); verifyNoMoreInteractions(atiServiceImpl); } }
错误栈信息
java.lang.NullPointerException: Cannot invoke "ru.se_nata.ati.service.AtiServiceImpl.findAllActHasForm()" because "this.atiServiceImpl" is null at ru.se_nata.ati.controller.AtiActHasFormControllerTest.findAllActHasForm(AtiActHasFormControllerTest.java:81) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) at java.base/java.lang.reflect.Method.invoke(Method.java:577) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60) at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
问题原因及解决方案
1. JUnit版本冲突导致注入失效
代码使用了JUnit 4的@RunWith(SpringJUnit4ClassRunner.class)注解,但错误栈显示测试运行在JUnit 5引擎下,版本冲突导致Spring无法正常注入atiServiceImpl实例。
修复方案:
替换为JUnit 5的Spring测试注解,简化测试配置:
@SpringBootTest @AutoConfigureMockMvc public class AtiActHasFormControllerTest { @Autowired private MockMvc mvc; // 其他代码保留 }
2. 未正确使用Mockito模拟服务
当前试图注入真实的AtiServiceImpl实例,但Controller测试场景应使用Mockito模拟服务,避免依赖真实业务逻辑。
修复方案:
使用@MockBean注解创建并注入模拟的服务实例:
@SpringBootTest @AutoConfigureMockMvc public class AtiActHasFormControllerTest { @Autowired private MockMvc mvc; @MockBean private AtiServiceImpl atiServiceImpl; // 测试方法无需修改,Mockito自动关联模拟对象 @Test void findAllActHasForm() throws Exception { Mockito.when(this.atiServiceImpl.findAllActHasForm()).thenReturn(getActHasForm()); // ... 原有断言代码 } }
3. 额外代码问题修正
forwardedUrl路径拼写错误:/resuorses/改为/resources/- 模型属性名错误:
model().attribute("todos", ...)改为model().attribute("acthasform", ...),与Controller返回的属性名一致
内容的提问来源于stack exchange,提问作者Natasha
相关产品推荐
相关产品推荐

