Fork me on GitHub

Getting Started

You have brand new class. Let's call it ClassTested.

public class ClassTested {

  private Collaborator listener;

  public void setListener(Collaborator listener) {
    this.listener = listener;
  }

  public void addDocument(String title, String document) {
    listener.documentAdded(title);
  }
}

Being a nice human being, you want to test your implementation. You might even be a disciple of TDD and haven't done your implementation yet. You want your test first!

Your tested class will depend on others so you figured you need a mocking framework. Good for you. Add EasyMock dependency to your POM file.

<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>5.4.0</version>
  <scope>test</scope>
</dependency>

Ok. Now addDocument should do stuff and then notify a dependency. Let's call it Collaborator.

public interface Collaborator {
    void documentAdded(String title);

Now, a word of warning. I will mock an interface in this example. That doesn't mean you should only mock interfaces. I hate useless interfaces. And you want me to be happy. Please don't create an interface just for the pleasure of mocking it. Just mock the concrete class. Thank you.

So, we want to make sure addDocument is notifying Collaborator by calling documentAdded with the right title in argument. Our todo list to do that:

  1. Create the mock
  2. Have it set to the tested class
  3. Record what we expect the mock to do
  4. Tell all mocks we are now doing the actual testing
  5. Test
  6. Make sure everything that was supposed to be called was called

Then the code fulfilling it:

import static org.easymock.EasyMock.*;
import org.easymock.*;
import org.junit.*;

public class ExampleTest extends EasyMockSupport {

    @Rule
    public EasyMockRule rule = new EasyMockRule(this);

    @Mock
    private Collaborator collaborator; // 1

    @TestSubject
    private ClassTested classUnderTest = new ClassTested(); // 2

    @Test
    public void addDocument() {
        collaborator.documentAdded("New Document"); // 3
        replayAll(); // 4
        classUnderTest.addDocument("New Document", "content"); // 5
        verifyAll(); // 6
    }
}

And that's all you need to get you started. Some comments though:

From there, I will highly suggest you have a look at the samples and the full documentation to get a fair overview of EasyMock.

Happy mocking!