46

I've been trying to figure out how to run parameterized tests in Junit4 together with PowerMock. The problem is that to use PowerMock you need to decorate your test class with

@RunWith(PowerMockRunner.class)

and to use parameterized tests you have to decorate with

@RunWith(Parameterized.class)

From what I can see they seem mutually excluded!? Is this true? Is there any way around this? I've tried to create a parameterized class within a class running with PowerMock; something like this:

@RunWith(PowerMockRunner.class)
class MyTestClass {
     @RunWith(Parameterized.class)
     class ParamTestClass {
          // Yadayada
     }
}

But unfortunately this doesn't do much good... The ParamTestClass still doesn't run with PowerMock support (not that surprisingly maybe)... And I've kind of run out of ideas so any help is greatly appreciated!

Update: For future googlers also see: Using PowerMock without the RunWith?

Andrii Abramov
  • 7,967
  • 8
  • 55
  • 79
Anders Hansson
  • 3,658
  • 3
  • 26
  • 27

4 Answers4

38

I had the same issue. Unfortunately it would not let me use a PowerMock Rule due to the JVM I had. Instead of the rule I used RunnerDelegate.

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)
tasomaniac
  • 9,559
  • 5
  • 45
  • 79
Abercrombieande
  • 581
  • 4
  • 12
  • Had the same JVM issue, this solution worked like a charm. Cheers! – Sean Connolly Jul 26 '15 at 08:56
  • This didn't work for me, because the tests asked to add `@PrepareForTest(StaticClass.class)` by adding below those annotation then this works. – Jonathan JOhx Sep 17 '19 at 23:05
  • This solution works well, also works with `pl.pragmatists` `JUnitParams`, just use this as the delegate: `@PowerMockRunnerDelegate(JUnitParamsRunner.class)` – jbaranski Apr 07 '21 at 14:30
16

Yes this works by using the PowerMock Rule available if you use JUnit 4.7+.

Walery Strauch
  • 5,317
  • 7
  • 45
  • 53
Johan
  • 185
  • 2
-1

You can't use two class runners at once, so you will definitely have to write your own test runner to make that happen.

I don't know anything about Powermock, but after 10 seconds of research, it looks like one solution would be to write a test runner which uses powermock's class loader and runs parameterized tests. If you can figure out how to delegate to the parameterized test runner from within your custom test runner, that might be your best bet.

Sean Reilly
  • 20,366
  • 3
  • 46
  • 61
-1

The following solution worked for me!

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)