我有一個文件Util.java
存根靜態方法調用:無法使用PowerMockito
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);
我試過這個解決方案,使用來自網絡的各種解決方案,但無法找到我的代碼中的錯誤。我需要將靜態方法的調用存根,因爲我需要它用於傳統代碼。 How do I mock a static method using PowerMockito?
我也試過這些。無效: 1.'PowerMockito.when(Util.class,MemberMatcher.method(Util.class,「returnString」))。withNoArguments()。thenReturn(「xyz」);' 2.'PowerMockito.doReturn(「 (Util.class,「returnString」);' 3.'doReturn(「xyz」)。when(Util.class); \t Util.returnString();' – Caesar