gpt4 book ai didi

java - 无法使用 PowerMockito stub 静态方法调用

转载 作者:行者123 更新时间:2023-12-02 04:02:15 27 4
gpt4 key购买 nike

我有一个文件Util.java:

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

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

另一类:

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);

我使用网络上的各种解决方案尝试了此解决方案,但无法找到代码中的错误。我需要 stub 静态方法的调用,因为我需要它来处理遗留代码。 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 .

关于java - 无法使用 PowerMockito stub 静态方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34773449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com