Unable to run JUnit test with PowerMockRunner

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

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 following exception when I add the @RunWith(org.powermock.modules.junit4.PowerMockRunner.class) annotation.

Error:

org.powermock.reflect.exceptions.FieldNotFoundException: Field 'fTestClass' was not found in class org.junit.internal.runners.MethodValidator. at org.powermock.reflect.internal.WhiteboxImpl.getInternalState(WhiteboxImpl.java:581) at org.powermock.reflect.Whitebox.getInternalState(Whitebox.java:308) at org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator.validate TestMethods(PowerMockJUnit4MethodValidator.java:79) at org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator.validate InstanceMethods(PowerMockJUnit4MethodValidator.java:49) at org.junit.internal.runners.MethodValidator.validateMethodsForDefaultRunner(MethodValidator.java:51) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.validate(PowerMockJUnit44RunnerDelegateImpl.java:108) ...

This are my test dependencies:

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

The test itself fails also when completely empty (initialization error):

@RunWith(PowerMockRunner.class) public class SomeTest {     @Test     public void testSomething() {     } }

Any ideas what might be wrong? Other tests using PowerMock are working fine (none of them uses the PowerMockRunner).

Greetings and thanks for any help! Ben

回答1:

This is a bug that occurs when you use JUnit 4.12 and PowerMock

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.



回答2:

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.



回答3:

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

@PrepareForTest({, ...})

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!