Unable to run JUnit test with PowerMockRunner

前端 未结 4 965
庸人自扰
庸人自扰 2020-12-03 09:23

I have a Gradle based Java project were I now want to mock a private method using PowerMock. The problem is that I am not able to use the PowerMockRunner as I always get the

相关标签:
4条回答
  • 2020-12-03 10:08

    There has been a bug logged against PowerMock: https://code.google.com/p/powermock/issues/detail?id=531

    It appears that JUnit changed some of its internal field names that PowerMock was accessing via reflection, thus breaking the ability for PowerMock to properly inject itself.

    0 讨论(0)
  • 2020-12-03 10:10

    Check what Stefan said, and above that you also need to add

    @PrepareForTest({<The class/es you are Mocking>, ...})
    

    without the prepare for test, PowerMockRunner won't know which class is mocked.

    0 讨论(0)
  • 2020-12-03 10:15

    There may also exist dependencies on classpath that override a JUnit specific class which contains JUnit's version. This leads to incorrect version comparison results in PowerMock. For instance, I had com.google.android.tools:dx:1.7 on classpath (came from hunspell library). It overrides following method return result:

    junit.runner.Version.id() => "3.8.1"
    

    Usually it should return something like "4.12" or "4.11" etc.

    0 讨论(0)
  • 2020-12-03 10:16

    This is a bug that occurs when you use JUnit 4.12 and PowerMock < 1.6.1. The problem is solved in PowerMock 1.6.1. Please update your dependencies accordingly

    testCompile 'junit:junit:4.12',
                'org.powermock:powermock-core:1.6.1',
                'org.powermock:powermock-module-junit4:1.6.1',
                'org.powermock:powermock-api-mockito:1.6.1'
    

    If you cannot upgrade PowerMock then you can use JUnit 4.11.

    testCompile 'junit:junit:4.11',
                'org.powermock:powermock-core:1.5.6',
                'org.powermock:powermock-module-junit4:1.5.6',
                'org.powermock:powermock-api-mockito:1.5.6'
    

    Could you please add further lines of the stacktrace, which uncover more details about the problem.

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