使用 PowerMock 模拟来自多个类的静态方法

我知道如何使用 PowerMock 模拟类中的静态方法。
但是我想使用 JUnit 和 PowerMock 模拟来自测试类中多个类的静态方法。

有没有人能告诉我,这是可能的,如何做到这一点?

79401 次浏览

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

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

etc...

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

If you are using kotlin, the syntax is this

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