无法使用 PowerMockito 存根静态方法调用

Unable to stub a static method call using PowerMockito

我有一个文件Util.java:

public class Util  {
    public static int returnInt() {
        return 1;
    }

    public static String returnString() {
        return "string";
    }
}

另一个class:

public class ClassToTest {
    public String methodToTest() {
        return Util.returnString();
    }
}

我想使用 TestNg 和 PowerMockito 对其进行测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
public class PharmacyConstantsTest {    
    ClassToTest classToTestSpy;

    @BeforeMethod
    public void beforeMethod() {
        classToTestSpy = spy(new ClassToTest());
    }

    @Test
    public void method() throws Exception {
        mockStatic(Util.class);
        when(Util.returnString()).thenReturn("xyz");
        classToTestSpy.methodToTest();
    }
}

但是,它抛出以下错误:

FAILED: method org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

我使用网络上的各种解决方案尝试了此解决方案,但无法在我的代码中找到错误。我需要对静态方法的调用进行存根,因为我需要它来处理遗留代码。 How do I mock a static method using PowerMockito?

您需要像这样配置 TestNG 以使用 PowerMock 对象工厂:

<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
    <test name="dgf">
        <classes>
            <class name="com.mycompany.Test1"/>
            <class name="com.mycompany.Test2"/>
        </classes>
    </test>
</suite>

在项目的 suite.xml 文件中。

请参考这个link

使用 PowerMockito 方法代替 Mockito 的方法。文档指出:

PowerMockito extends Mockito functionality with several new features such as mocking static and private methods and more. Use PowerMock instead of Mockito where applicable.

每个实例:

PowerMockito.when(Util.returnString()).thenReturn("xyz");

仅作记录,添加使测试 class 成为 PowerMockTestCase 的子 class 对我有用。

@PrepareForTest(Util.class)
public class PharmacyConstantsTest extends PowerMockTestCase {    
    ClassToTest classToTestSpy;

    @BeforeMethod
    public void beforeMethod() {
        classToTestSpy = spy(new ClassToTest());
    }

    @Test
    public void method() throws Exception {
        mockStatic(Util.class);
        when(Util.returnString()).thenReturn("xyz");
        classToTestSpy.methodToTest();
     }
 }