Mockito when语句Maven构建触发Method.getParameterTypes()空指针,Eclipse正常
单元测试在Eclipse中正常执行,但Maven构建时抛出空指针异常(Mockito v5.5.0)
问题背景
维护的单元测试在Eclipse中运行无异常,但使用Maven构建时抛出空指针异常,当前使用Mockito核心版本v5.5.0。
出错代码
测试方法
@Test public void testfilterFeatureEnabled() throws Exception { when(featureToggle.havingValue()).thenReturn("stuff"); when(activationStrategy.isApplicable(any(Feature.class))).thenReturn(true); // 54行,异常触发处 when(activationStrategy.havingValue(any(Feature.class), anyString())).thenReturn(true); featureToggleFilter.filter(reqContext); verify(reqContext, never()).abortWith(any(Response.class)); }
测试类Mock定义
@ExtendWith(MockitoExtension.class) public class FeatureToggleFilterTest { @InjectMocks private FeatureToggleFilter featureToggleFilter; @Mock private FeatureToggle featureToggle; @Mock private ActivationStrategy activationStrategy; @Mock private ContainerRequestContext reqContext; }
Maven构建堆栈信息
java.lang.NullPointerException at java.base/java.lang.reflect.Method.getParameterTypes(Method.java:311) at org.mockito.internal.creation.DelegatingMethod.<init>(DelegatingMethod.java:20) at org.mockito.internal.invocation.DefaultInvocationFactory.createMockitoMethod(DefaultInvocationFactory.java:81) at org.mockito.internal.invocation.DefaultInvocationFactory.createInvocation(DefaultInvocationFactory.java:60) at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:83) at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:56) at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:161) at com.att.idp.featuretoggle.core.ActivationStrategy$MockitoMock$4gFdat1K.isApplicable(Unknown Source) at com.att.idp.featuretoggle.web.jaxrs.FeatureToggleFilterTest.testfilterFeatureEnabled(FeatureToggleFilterTest.java:54)
异常触发于测试代码第54行,排查发现是Method.getParameterTypes()调用时抛出NPE,推测关联的Method实例被Mock导致。
解决方法
在Maven Surefire插件配置中添加进程隔离相关属性,强制测试在独立进程中运行即可解决问题。示例配置如下:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <!-- 使用对应版本的Surefire插件 --> <configuration> <forkCount>1</forkCount> <reuseForks>true</reuseForks> </configuration> </plugin> </plugins> </build>
内容的提问来源于stack exchange,提问作者David M. Karr
相关产品推荐
相关产品推荐

