6
votes

I need to mock a static method of a class and use that mocked method in my test. Right now seems I can only use PowerMock to do that.

I annotate the class with @RunWith(PowerMockRunner.class), and @PrepareForTest with the appropriate class.

In my test I have a @ClassRule, but when running the tests, the rule is not applied properly.

What can i do ?

    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
3
Just for tracing: github.com/powermock/powermock/issues/687 . PowerMock basically breaks JUnit test handling, and there is no real plan to fix it.Damien B

3 Answers

5
votes

Another way of working around this problem is to use the org.powermock.modules.junit4.PowerMockRunnerDelegate annotation:

@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
3
votes

I looked into the PowerMock code. It looks like PowerMockRunner does not support @ClassRule. You can try to use the HibernateSessionRule as a @Rule instead of a @ClassRule.

@PrepareForTest(Request.class)
public class RoleTest {

  @Rule
  public HibernateSessionRule sessionRule = new HibernateSessionRule();
-1
votes

I found another solution only valid with PowerMock 1.4 or major. I added these dependencies to my 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>

and changed my code removing @RunWith annotation and using a simple JUnit @Rule

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

    // Tests goes here
    ...
}

for more information visit PowerMock's documentation