Mockito + PowerMock LinkageError while mocking system class

后端 未结 6 1815
难免孤独
难免孤独 2020-12-12 10:28

I\'ve got such a code snippet:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Thread.class})
public class AllMeasuresDataTest {

@Before
public void setUp(         


        
相关标签:
6条回答
  • 2020-12-12 11:17

    In order to mock system classes, prepare the class that is the target of the test, not Thread.class. There's no way PowerMock will be able to instrument Thread.class because it is required during JVM startup - well before PowerMock can instrument.

    The way instrumentation works, once a class is loaded, it can no longer be intstrumented.

    See the PowerMock wiki.

    0 讨论(0)
  • 2020-12-12 11:19

    This may be a bit of an old topic, but I have also ran into this problem. Turns out that some of the java versions cannot handle powermockito when powermock finds out there are 2 classes with the same name in the same package (over different dependencies).

    With any version higher than Java 7_25 it gives this error.

    0 讨论(0)
  • 2020-12-12 11:21

    Try adding this annotation to your Test class:

    @PowerMockIgnore("javax.management.*")

    Worked for me.

    0 讨论(0)
  • 2020-12-12 11:23

    Classloader conflict, use this: @PowerMockIgnore("javax.management.*")

    Let mock classloader do not load javax.*. It works.

    0 讨论(0)
  • 2020-12-12 11:29

    In PowerMock 1.7.0 a user-defined global configuration can be added to your project's classpath. PowerMockConfig

    org/powermock/extensions/configuration.properties
    

    Simply add a line in the properties file like:

    powermock.global-ignore=javax.management.*
    

    This will resolve the error for all the test classes in your project.

    0 讨论(0)
  • 2020-12-12 11:33

    Similar to the accepted response here, I ended up having to exclude all of the SSL related classes:

    @PowerMockIgnore({"javax.management.*", "org.apache.http.conn.ssl.*", "com.amazonaws.http.conn.ssl.*", "javax.net.ssl.*"})
    

    Adding that to the top of my class resolved the error.

    0 讨论(0)
提交回复
热议问题