PowerMockRunner 不应用 JUnit ClassRules

PowerMockRunner does not apply JUnit ClassRules

我需要模拟 class 的静态方法并在我的测试中使用该模拟方法。现在看来我只能使用 PowerMock 来做到这一点。

我用@RunWith(PowerMockRunner.class) 注释 class,并用适当的 class.

注释 @PrepareForTest

在我的测试中我有一个@ClassRule,但是当 运行 测试时,规则没有正确应用。

我能做什么?

    RunWith(PowerMockRunner.class)
@PowerMockIgnore({
    "javax.xml.*",
    "org.xml.*",
    "org.w3c.*",
    "javax.management.*"
})
@PrepareForTest(Request.class)
public class RoleTest {

    @ClassRule
    public static HibernateSessionRule sessionRule = new HibernateSessionRule(); // this Rule doesnt applied

我查看了 PowerMock 代码。看起来 PowerMockRunner 不支持 @ClassRule。您可以尝试将 HibernateSessionRule 用作 @Rule 而不是 @ClassRule.

@PrepareForTest(Request.class)
public class RoleTest {

  @Rule
  public HibernateSessionRule sessionRule = new HibernateSessionRule();

解决此问题的另一种方法是使用 org.powermock.modules.junit4.PowerMockRunnerDelegate 注释:

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PowerMockIgnore({
    "javax.xml.*",
    "org.xml.*",
    "org.w3c.*",
    "javax.management.*"
})
@PrepareForTest(Request.class)
public class RoleTest {

    @ClassRule
    public static HibernateSessionRule sessionRule = new HibernateSessionRule(); // this Rule now applied

我找到了另一个只对 PowerMock 1.4 或主要版本有效的解决方案。我将这些依赖项添加到我的 pom.xml

<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4-rule</artifactId>
  <version>2.0.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-classloading-xstream</artifactId>
  <version>2.0.2</version>
  <scope>test</scope>
</dependency>

并更改了我的代码,删除了 @RunWith 注释并使用了一个简单的 JUnit @Rule

@PrepareForTest(X.class);
public class MyTest {
    @Rule
    PowerMockRule rule = new PowerMockRule();

    // Tests goes here
    ...
}

有关详细信息,请访问 PowerMock 的 documentation