106
votes

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?

4
You just do it in the same way you mock methods from single classes. Where are you stuck? - artbristol
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

4 Answers

266
votes

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

13
votes
@Test
 @PrepareForTest({Class1.class, Class2.class})
 public final void handleScript() throws Exception {
    PowerMockito.mockStatic(Class1.class);
    PowerMockito.mockStatic(Class2.class);

etc...

2
votes

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() {
  }
}
2
votes

If you are using kotlin, the syntax is this

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