Reputation: 1092
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?
Upvotes: 0
Views: 1840
Reputation: 1092
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();
}
}
Upvotes: 1
Reputation: 12202
Use PowerMockito methods instead of the Mockito's. The docs states that:
PowerMockito extends Mockito functionality with several new features such as mocking static and private methods and more. Use PowerMock instead of Mockito where applicable.
Per instance:
PowerMockito.when(Util.returnString()).thenReturn("xyz");
Upvotes: -1
Reputation: 6005
You need to configure TestNG to use the PowerMock object factory like this:
<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>
in your suite.xml file of the project.
Please refer this link.
Upvotes: 1