【问题标题】:PowerMockRunner does not apply JUnit ClassRulesPowerMockRunner 不适用 JUnit ClassRules
【发布时间】:2016-12-10 20:29:06
【问题描述】:

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

我使用@RunWith(PowerMockRunner.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

【问题讨论】:

标签: java junit powermockito


【解决方案1】:

解决此问题的另一种方法是使用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

【讨论】:

    【解决方案2】:

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

    @PrepareForTest(Request.class)
    public class RoleTest {
    
      @Rule
      public HibernateSessionRule sessionRule = new HibernateSessionRule();
    

    【讨论】:

      【解决方案3】:

      我发现另一种解决方案仅适用于 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-29
        • 1970-01-01
        • 2010-12-20
        • 2019-05-12
        • 2019-01-24
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多