Reputation: 228
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
Upvotes: 6
Views: 2751
Reputation: 2157
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
Upvotes: 0
Reputation: 19445
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
Upvotes: 6
Reputation: 24540
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();
Upvotes: 3