PowerMockRule

Arthur Zagretdinov edited this page Aug 13, 2017 · 11 revisions

Bootstrapping using a JUnit Rule

   Feature avaliable since PowerMock 1.4

Since version 1.4 it's possible to bootstrap PowerMock using a JUnit Rule instead of using the PowerMockRunner and the RunWith annotation. This allows you to use other JUnit runners while still benefiting from PowerMock's functionality. You do this by specifying:

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

    // Tests goes here
    ...
}

Using PowerMockRule with Maven

You need to depend on these projects:

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

You can also replace powermock-classloading-xstream with an Objenesis version:

<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-classloading-objenesis</artifactId>
  <version>1.7.1</version>
  <scope>test</scope>
</dependency>

However this version is not as stable as the xstream version but it does not require any additional dependencies.

Warning: Use version PowerMock 1.4 (or later) since prior to this version the rule did not actually execute any test methods (but it looked like it did).

Using PowerMockRule without Maven

You need to download powermock-module-junit4-rule, powermock-classloading-base and one of
powermock-classloading-xstream or powermock-classloading-objenesis and put it in your classpath.

References