EasyMock Annotations - JUnit 4 With Examples

EasyMock annotations can be used to create Mock objects. We can also tell the EasyMock framework to inject these mock objects into another concrete class.

EasyMock Annotations

There are two important EasyMock annotations that we should be aware of:

  1. @Mock: Used to specify a field to be mocked by EasyMock.
  2. @TestSubject: Used to specify an object where we want EasyMock to inject mocked objects created using @Mock annotation.

EasyMock Annotations Example

When we use EasyMock annotations, we have to explicitly initialize them through one of the following methods.

  1. @RunWith(EasyMockRunner.class): We can use this if we are using JUnit 4, note that JUnit 5 still doesn’t support this. If we use this with JUnit 5, then it will fallback to use JUnit 4 runner classes.
  2. org.easymock.EasyMockRule: This utilizes JUnit 4 Rule, so again it can’t be used with JUnit 5.
  3. EasyMockSupport.injectMocks(this): We can use this in @Before methods to tell EasyMock to inject mock objects. This is the preferred way for JUnit 5 and TestNG frameworks.

Let’s look at the example of using all the above-mentioned methods to create mock objects using EasyMock.

First of all, we will create some classes to mock. I will be using JUnit 4 for our example so that I can showcase all the three ways of creating mock objects through EasyMock annotations.

We will create mock objects of the above interfaces and inject them into the following concrete class.


Here is the test class using @RunWith(EasyMockRunner.class) with EasyMock annotations.

Notice that behavior stubbing is done on the mocked objects. They are being called internally when we are invoking methods on the TestSubject object.


Here is the code snippet to use EasyMockRule. I have removed code from test method because they are same as earlier test method.


This way of creating mocks will work with JUnit 5 as well as TestNG testing framework.


EasyMock annotations allow us to create mocks at the global level, we can reuse these mocks in different test methods as well as inject them into various other objects dependent on them.

By admin

Leave a Reply

%d bloggers like this: