PowerMockRule JDK 11

PowerMockRule with JDK 11

我使用 PowerMockRule 来覆盖单元测试,该单元测试在 JDK 8 中运行良好,但是当我使用 JDK 11 升级我的应用程序时,它开始无法通过单元测试。

我用 power mock 尝试了几个依赖组合,但没有任何效果。试图找出根本原因和解决方案。有人可以帮我解决这个问题吗?

进入 JDK 11

时出错
java.io.RuntimeException: java.io.IOException: Can not attach to current VM
at org.powermock.modules.agent.AgentLoader.attachToThisVM(AgentLoader.java:140)
at org.powermock.modules.agent.AgentLoader.loadAgent(AgentLoader.java:87)
at org.powermock.modules.agent.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:40)

下面是一个简单的单元测试(不适合复杂的单元测试 - 但即使是简单的单元测试也会出现相同的错误)

class PowerMockSimpleSpec extend Specification {

  @Rule
  public PowerMockRule rule = new PowerMockRule()  

  def "one plus one should equal two"() {
    expect:
    1 + 1 == 2
  }
}

依赖项适用于 JDK 8 但不适用于 JDK 11

testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9'
testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9'
testImplementation group: 'org.powermock', name: 'powermock-module-junit4-rule-agent', version: '2.0.9'

尝试添加以下依赖项但运气不好

testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9'
testImplementation group: 'org.powermock', name: 'powermock-module-junit4-rule', version: '2.0.9'
testImplementation group: 'org.powermock', name: 'powermock-classloading-xstream', version: '2.0.9'

也参考了下面的文档,但再次没有运气 depedencies https://github.com/powermock/powermock/wiki/PowerMockRule

看来您需要添加 -Djdk.attach.allowAttachSelf=true

https://github.com/powermock/powermock/issues/979#issuecomment-485678666