EasyMock Private Method Mock using PowerMock

Sometimes we want to test a method that is using a private method. We can create the mock object using EasyMock but EasyMock doesn’t allow us to mock private methods. So we can use PowerMock EasyMock API extension to mock a class private methods.

EasyMock Private Method Mock using PowerMock

For stubbing private method behavior, we have to use PowerMock.createPartialMock() to get the mock object. This is required so that we don’t mock the methods where these private methods are being called.

After that, use PowerMock.expectPrivate() method to stub the private method behavior.

Make sure to call PowerMock.replay() before writing the test code that uses the stubbed methods. For stub methods call verification, use PowerMock.verify() method.

EasyMock Private Method – JUnit 4

PowerMock doesn’t support JUnit 5 as of now, so I will use JUnit 4 for writing test cases.

Let’s say we have a class defined as:

Notice that the public methods are internally calling the class private methods.

Here is the test class where we are mocking the private method behaviors.

Notice that we are creating partial mock for only private methods, public methods are not mocked. So when we call these public methods, the real method will get called that will internally call the private method and our stubbed method implementation will be used.

EasyMock Private Method – TestNG

Here is the example of mocking private method written in TestNG testing framework.

Notice that the TestNG class is extending PowerMockTestCase class, so that PowerMock API is used to run the test cases.

Summary

PowerMock is a great extension API for EasyMock and Mockito mocking frameworks. It’s easily integrated with EasyMock and JUnit/TestNG frameworks. I hope they start supporting JUnit 5 real soon.

You can checkout complete project and more EasyMock examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: