EasyMock Final Method - PowerMock, JUnit 4, TestNG With Examples

One of the limitations of EasyMock is that it can’t mock final methods and final classes. However, we can use PowerMock EasyMock extension to mock static methods.

EasyMock Final Method and Class using PowerMock

PowerMock is divided into multiple modules to support JUnit and TestNG testing framework. Similarly, there are modules to extend EasyMock and Mockito mocking frameworks.

I will provide an example to mock final method inside a final class using PowerMock on both JUnit 4 and TestNG frameworks. So we need to import the following artifacts.

  • powermock-module-junit4
  • powermock-module-testng
  • powermock-api-easymock
  • junit, testng and easymock for obvious reasons.

I am not using JUnit 5 because PowerMock doesn’t support it yet. I am using the following versions for my examples.

JUnit PowerMock EasyMock Final Method Example

  • First step is to annotate test class with @RunWith(PowerMockRunner.class) annotation.
  • Next step is to specify the classes to prepare for testing using PowerMock, for example @PrepareForTest(Data.class). This has to be done at the class level and we can use its fullyQualifiedNames to specify multiple classes and packages.
  • In the test method, use PowerMock.createMock() method to mock the final class.
  • Stub the behaviors using EasyMock.expect() method.
  • Use PowerMock.replay() to finalize the mock object and its behavior setup.
  • Use JUnit 4 asserts to test the behaviors.
  • Use PowerMock.verify() to verify that all the stubbed final methods were called.

Let’s say we have a final class as:

Here is the JUnit test to mock the final class and its final method and test it.

TestNG PowerMock EasyMock Final Method Example

If you want to use TestNG instead of JUnit-4, then make sure your test class extends PowerMockTestCase class. Also remove the @RunWith annotation. Make necessary changes to other annotations and use TestNG assert methods.

Below class uses TestNG along with PowerMock to mock final methods using EasyMock.


PowerMock is a great extension to EasyMock and Mockito mocking frameworks. It helps us to extend our test cases to cover final classes and final methods too.

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

By admin

Leave a Reply

%d bloggers like this: