Home > Java > javaTutorial > How to Effectively Mock Private Methods with PowerMock and Mockito?

How to Effectively Mock Private Methods with PowerMock and Mockito?

Linda Hamilton
Release: 2024-11-03 19:19:03
Original
293 people have browsed it

How to Effectively Mock Private Methods with PowerMock and Mockito?

Alternative Solution for Mocking Private Methods with PowerMock

Despite encountering difficulties with the initially proposed solution using PowerMock, an alternative approach has proven successful. Using a combination of Mockito and PowerMock, it is possible to mock private methods effectively.

As illustrated in the provided code snippet, the class CodeWithPrivateMethod possesses a public method meaningfulPublicApi that invokes a private method doTheGamble. To mock the behavior of doTheGamble, the test class CodeWithPrivateMethodTest utilizes PowerMock to spy on an instance of the original class and uses Mockito to specify the desired return value.

In this specific scenario, when the private method doTheGamble is called with any string and integer arguments, it is instructed to return true. This causes the public method meaningfulPublicApi to trigger a RuntimeException.

The complete test configuration is accomplished through PowerMock's @PrepareForTest annotation, which ensures that the class under test is prepared for spying. The test is executed using the PowerMockRunner, which facilitates mocking of static and private methods.

The above is the detailed content of How to Effectively Mock Private Methods with PowerMock and Mockito?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template