Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMockRunner does not apply JUnit ClassRules

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
like image 749
Yusuf Azal Avatar asked Aug 04 '16 15:08

Yusuf Azal


2 Answers

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
like image 100
Steve C Avatar answered Nov 03 '22 12:11

Steve C


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();
like image 41
Stefan Birkner Avatar answered Nov 03 '22 12:11

Stefan Birkner