111

I know how to mock static methods from a class using PowerMock.
But I want to mock static methods from multiple classes in a test class using JUnit and PowerMock.

Can anyone tell me is it possible to do this and how to do it?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Newbie
  • 2,979
  • 9
  • 34
  • 41
  • 1
    You just do it in the same way you mock methods from single classes. Where are you stuck? – artbristol Apr 26 '12 at 07:42
  • When using powermock, you need to add this annotation to the test class @PrepareForTest(ClassThatContainsStaticMethod.class). But we cannot specify multiple annotations. So how to do it? – Newbie Apr 26 '12 at 08:16

4 Answers4

271

Just do @PrepareForTest({Class1.class,Class2.class}) for multiple classes.

artbristol
  • 32,010
  • 5
  • 70
  • 103
  • 12
    curly braces! that's what I was missing. – sudocoder Jan 17 '14 at 20:28
  • 2
    Also don't forget to switch to PowerMockRunner with `@RunWith(PowerMockRunner.class)` on the class level – Nikita Barishok Oct 27 '16 at 14:22
  • 1
    @NikitaBarishok not always needed. You can define a rule instead to make above work -`@Rule public PowerMockRule rule = new PowerMockRule();` – Aniket Thakur Apr 09 '17 at 15:10
  • 5
    in kotlin `@PrepareForTest(Class1::class, Class2::class))` – Ryhan Sep 13 '17 at 20:40
  • It is also better to use `@PrepareOnlyThisForTest` instead of `@PrepareForTest`. The latter also modifies superclasses, which is not normally needed. – Leo Dec 13 '17 at 09:11
  • But I am getting **java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=test], {ExactMatcher:fDisplayName=test(aero.tav.tams.task.manager.PMTest)], {LeadingIdentifierMatcher:fClassName=aero.tav.tams.task.manager.PMTest,fLeadingIdentifier=test]] from org.junit.internal.requests.ClassRequest@dc9876b at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)** when I add a specific class. If I remove the class it is working. – ceyun Jun 03 '20 at 11:55
14
@Test
 @PrepareForTest({Class1.class, Class2.class})
 public final void handleScript() throws Exception {
    PowerMockito.mockStatic(Class1.class);
    PowerMockito.mockStatic(Class2.class);

etc...

arush436
  • 1,748
  • 20
  • 20
4

If you are using kotlin, the syntax is this

@PrepareForTest(ClassA::class, ClassB::class)

Ezio
  • 2,837
  • 2
  • 29
  • 45
2

In java with powermock/junit, use @PrepareForTest({}) with as many static classes as you want as array ({}).

@RunWith(PowerMockRunner.class)
@PrepareForTest({XmlConverterA.class, XmlConverterB.class})
class TransfersServiceExceptionSpec {

}

I have used powermock with in scala/junit, as scalatest does not have integration with powermock.

@RunWith(classOf[PowerMockRunner])
@PrepareForTest(Array(classOf[XmlConverterA], classOf[XmlConverterB]))
class TransfersServiceExceptionSpec {

  @Test
  def test() {
  }
}
prayagupa
  • 30,204
  • 14
  • 155
  • 192