Home >Java >javaTutorial >How to Mock Private Methods in Mockito with PowerMock?
Mocking Private Methods in Mockito with PowerMock
Testing classes with private methods can pose a challenge, especially when the correctness of those private methods is assumed. One solution to this is using PowerMock in conjunction with Mockito.
To mock a private method using PowerMock, follow these steps:
Use PowerMockito.when(): Define the behavior of the private method using PowerMockito.when(). This method takes three parameters:
For example, the following code mocks the private method "doTheGamble" to always return true:
<code class="java">CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod()); when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class)) .withArguments(anyString(), anyInt()) .thenReturn(true);</code>
By following these steps, you can effectively mock private methods for testing using PowerMock and Mockito.
The above is the detailed content of How to Mock Private Methods in Mockito with PowerMock?. For more information, please follow other related articles on the PHP Chinese website!