【问题标题】:Powermock - trying to mock method actually calls methodPowermock - 试图模拟方法实际上调用方法
【发布时间】:2018-09-18 15:29:55
【问题描述】:

我有一个带有静态方法的简单类,通常会抛出一个空指针:

public class MyClass {
    private static String s;

    public static final int myMethod(){
        return s.length();
    }
}

我试图像这样使用 PowerMock 模拟这个静态方法:

import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyClass.class })

public class MyClassTest {
    @Test
    public void test() {
        PowerMockito.mock(MyClass.class);
        when(MyClass.myMethod()).thenReturn(3);
        System.out.println(MyClass.myMethod());
    }
}

但结果是:

java.lang.NullPointerException
    at MyClass.myMethod(MyClass.java:6)
    at MyClassTest.test(MyClassTest.java:20)

所以当我试图模拟它时,似乎调用了实际的方法。为什么会这样?

【问题讨论】:

  • 您应该只模拟依赖项,您的测试对象中的方法不适合模拟。

标签: java mocking mockito powermock


【解决方案1】:

问题是我需要使用 PowerMockito.mockStatic 而不是 PowerMockito.mock。

【讨论】:

    【解决方案2】:
    public void test() {
            MyClass mockedClass = PowerMockito.mock(MyClass.class);
            when(mockedClass.myMethod()).thenReturn(3);
            System.out.println(MyClass.myMethod());
        }
    

    【讨论】:

    • 还是同样的问题。
    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多