Getting javassist.NotFoundException with PowerMock and PowerRule in JUnit with Mockito

China☆狼群 提交于 2019-11-29 07:04:17

Found out the solution myself:

Use the below dependencies (for Power Mock and Power Rule) only

    <!-- Required for PowerMock -->
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- Required for PowerMockRule -->
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-rule-agent</artifactId>
        <version>1.4.12</version>
        <scope>test</scope>
    </dependency>

Now I am not getting either of the above exceptions

Replace powermock-module-junit4-rule with powermock-module-junit4-rule-agent.

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4-rule-agent</artifactId>
    <scope>test</scope>
</dependency>

The main difference between the agent based bootstrapper and the classloading based bootstrapper is that you don't run into classloading issues.

Without more code samples I gather that the code is using Spring in the test. So I believe the reason for this error is that related to Spring use, which do seem to have generated JDK proxies (the $Proxy88).

And the way Powermock is working is by running the JUnit test in a new classloader in order to modify the bytecode of these classes, unfortunately it is only possible to modify the bytecode from a the real file, or at least from a location where it's possible to read the class binary, as java cannot access bytecode already loaded in the JVM. (It may be possible with an agent in a limited way).

As JDK proxies do not exists on disk, they cannot be read, or copied to the specific Powermock classloader.

The test you are writing is not a unit test as it is run with a Spring context. You might want to write a real Unit Test first. Then some Integration Test, in which you won't need mocks.

Also you should avoid the use of statics, as it is a testability nightmare. You should rewrite your production code in a way where static calls don't need to be mocked.

Cheers,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/test-servlet.xml")
public class ControlCenterManagerImplTest {

@Rule
public  PowerMockRule rule = new PowerMockRule();

//Powermock agent initialization not required and using maven dependency specified above by BHUVAN we can execute Power mock using spring.}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!