PowerMock throws NoSuchMethodError (setMockName)

2022-09-02 05:04:29

我试图模拟一个构造函数,但每次我运行测试时,我都会得到以下错误:PowerMockito

java.lang.NoSuchMethodError: org.mockito.internal.creation.MockSettingsImpl.setMockName(Lorg/mockito/mock/MockName;)Lorg/mockito/internal/creation/settings/CreationSettings;
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:107)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.createNewSubstituteMock(DefaultConstructorExpectationSetup.java:105)
at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.withAnyArguments(DefaultConstructorExpectationSetup.java:71)

我的项目中有以下PowerMock依赖项:

  • org.powermock:powermock-module-junit4:1.5.6
  • org.powermock:powermock-mockito-release-full:1.5.6

我已经跟踪了项目的依赖关系树并修复了冲突,以便将其包含在构建中。mockito-all:1.9.5


答案 1

确保 powermockitomockito 版本与此版本图表中一致 - MockitoUsage#supported-versions

Mockito                     | PowerMock
------------------------------------------------------------------------------
2.0.0-beta - 2.0.42-beta    |   1.6.5+
------------------------------------------------------------------------------
1.10.19                     |   1.6.4
1.10.8 - 1.10.x             |   1.6.2+
1.9.5-rc1 - 1.9.5           |   1.5.0 - 1.5.6
1.9.0-rc1 & 1.9.0           |   1.4.10 - 1.4.12
1.8.5                       |   1.3.9 - 1.4.9
1.8.4                       |   1.3.7 & 1.3.8
1.8.3                       |   1.3.6
1.8.1 & 1.8.2               |   1.3.5
1.8                         |   1.3
1.7                         |   1.2.5

使用maven查找和版本的简单方法是,mockitopowermock-mockito

mvn dependency:tree | grep mockito
[INFO] |  \- org.mockito:mockito-core:jar:1.8.5:compile
[INFO] +- org.mockito:mockito-all:jar:1.8.5:compile
[INFO] +- org.powermock:powermock-api-mockito:jar:1.4.9:compile

问题可能是应用程序中 mockito 的版本与 powermockito 使用的版本冲突,在我使用不支持 mockito 1.8.5 的 powermock 1.6.5 的情况下,冲突如下

mvn clean dependency:tree | grep mockito
[INFO] +- org.mockito:mockito-all:jar:1.8.5:compile

[INFO] \- org.powermock:powermock-api-mockito:jar:1.6.5:compile
[INFO]    +- org.mockito:mockito-core:jar:1.10.19:compile
[INFO]    \- org.powermock:powermock-api-mockito-common:jar:1.6.5:compile

答案 2

我有

org.mockito mockito-all 1.8.4

添加到我的pom.xml除了powermock的依赖性之外,删除这个对我有用。


推荐