如何在PowerMockito中模拟身份验证对象?

时间:2018-06-22 16:54:18

标签: java unit-testing powermockito

请注意,这是一个UNIT测试,而不是集成测试,因此,我不希望有任何Spring,而实际上所有可以被嘲笑的东西都应该如此。

此代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest({...})
@PowerMockIgnore({
        "com.sun.crypto.*",
        "javax.crypto.*",
        "javax.management.*"})
public class TestClass {
...


@Test
public void testMethod (
          Authentication mockAuthentication = Mockito
                .mock(Authentication.class);  
  ) 
}

...引发此异常:

java.lang.LinkageError: loader constraint violation: loader (instance of org/powermock/core/classloader/MockClassLoader) previously initiated loading for a different type with name "javax/security/auth/Subject"

    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:262)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:206)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.springframework.security.authentication.TestingAuthenticationToken$MockitoMock$2107019845.<clinit>(Unknown Source)
    at sun.reflect.GeneratedSerializationConstructorAccessor27.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
    at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:18)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:47)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
    at org.mockito.Mockito.mock(Mockito.java:1729)
    at org.mockito.Mockito.mock(Mockito.java:1642)

线索?我一直在尝试StackOverflow的各种方法,但尚未找到解决方案。 当然,PowerMockito使用此类来发挥它的魔力,所以也许它是由PowerMockito加载的并且无法更改?

1 个答案:

答案 0 :(得分:4)

在这种情况下,不加载的类属于javax.security,因此您应该忽略@PowerMockIgnore中的“ javax.security。*”。可以。