Home  >  Article  >  Java  >  How to Mock Private Methods in Mockito with PowerMock?

How to Mock Private Methods in Mockito with PowerMock?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 16:00:30253browse

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:

  1. Create a spy object: Use PowerMockito.spy() to create a spy object of the class you want to test.
  2. Use PowerMockito.when(): Define the behavior of the private method using PowerMockito.when(). This method takes three parameters:

    • The spy object
    • A method matcher (in this case, a method() matcher will suffice)
    • The behavior to return when the private method is called

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>
  1. Test the public method: Finally, you can use your spy object to test the public method that calls the private one.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn