I have a file Util.java
:
public class Util {
public static int returnInt() {
return 1;
}
public static String returnString() {
return "string";
}
}
Another class:
public class ClassToTest {
public String methodToTest() {
return Util.returnString();
}
}
I want to test it using TestNg and 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();
}
}
However, it throws the following error:
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);
I tried this solution using various solutions from the web, but could not locate the mistake in my code. I need to stub the call for static method, since I need it for a legacy code. How do I mock a static method using PowerMockito?
Just for the record, adding making the test class a subclass of PowerMockTestCase
worked for me.
@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();
}
}