Java:模拟静态方法和链接方法

时间:2019-11-12 14:24:59

标签: mockito junit4 powermockito

我想嘲笑我的class FilterFilter filter = Mockito.spy(new Filter());

Filter的构造函数中(这是我的问题):

public Filter() {
    this.gameConfig = FactoryProvider.of().getConfigFactory().createGameConfig();
}

FactoryProvider是工厂的工厂。静态方法 {of() 返回FactoryProvider的实例。 getConfigFactory()返回ConfigFactory的实例 并且createGameConfig()返回GameConfig

的实例

我的想法是这个:

public class FilterTest {

@Spy
FactoryProvider factoryProvider;

@Before
public void setUp() {
    when(FactoryProvider.of()).thenReturn(factoryProvider);
    when(factoryProvider.getConfigFactory()).thenReturn(new FakeFactory());
}

public static class FakeFactory extends ConfigFactory {
    public GameConfig createGameConfig() {
        return new GameConfig();
    }
}

@Test
public myTest() {
    Filter filter = Mockito.spy(new Filter());
   /////////////////

失败,并且出现此错误:

java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler@13d73fa failed.
    at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:84)

0 个答案:

没有答案