我正在尝试使用 PowerMockito 来模拟静态调用。但是,当我尝试这样做时,PowerMockito.mockStatic
调用会引发 AbstractMethodError:
java.lang.AbstractMethodError: org.mockito.configuration.MockitoConfiguration.enableClassCache()Z
at org.mockito.internal.configuration.GlobalConfiguration.enableClassCache(GlobalConfiguration.java:63)
at org.mockito.internal.creation.instance.ObjenesisInstantiator.<init>(ObjenesisInstantiator.java:11)
at org.mockito.internal.creation.instance.InstantiatorProvider.<clinit>(InstantiatorProvider.java:7)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:110)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:58)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
由于这是我在单元测试方法中做的第一件事,它实际上还没有与我自己的任何代码进行交互。
我试图模拟的类不在 Spring 安全库中:SecurityContextHolder
.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ SecurityContextHolder.class })
@PowerMockIgnore({ "org.slf4j.*", "javax.management.*", "org.apache.log4j.*"})
public class AuthorizationSuccessHandlerTest {
@Test
public void testAuthenticationSuccess() throws Exception {
// this first line throws the exception:
PowerMockito.mockStatic(SecurityContextHolder.class);
SecurityContext mockContext = Mockito.mock(SecurityContext.class);
Mockito.when(SecurityContextHolder.getContext()).thenReturn(mockContext);
// .. other stuff to follow that we never get to
}
}
我有以下 Maven 依赖项:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
(在这个测试中没有使用 EasyMock 的东西,但我将它们包括在内以防出现某种冲突。我已经尝试了 mockito-all 和 mockito-core,在行为上没有明显的差异。删除直接的 mockito依赖(mockito-all 或 mockit-core)也没有区别。)
我究竟做错了什么?