--- layout: default title: Getting started comments: true locale: en ---

Getting Started

Add EasyMock dependency to your POM file.

{% highlight xml %} org.easymock easymock {{site.latest_version}} test {% endhighlight %}

Then, you need a class to test and a collaborator used by this class. The collaborator can be a class or an interface. It doesn't matter. Please don't create an interface just for the pleasure of mocking it.

{% highlight java %} public interface Collaborator { void documentAdded(String title); } public class ClassUnderTest { private Collaborator listener; // ... public void setListener(Collaborator listener) { this.listener = listener; } public void addDocument(String title, byte[] document) { // ... } } {% endhighlight %}

In our case, we are expecting the collaborator to be notified when a document is added to the class under test. So lets do that. First our todo list:

  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:

{% highlight java %} import static org.easymock.EasyMock.*; import org.easymock.*; import org.junit.Rule; import org.junit.Test; public class ExampleTest extends EasyMockSupport { @Rule public EasyMockRule rule = new EasyMockRule(this); @Mock private Collaborator collaborator; // 1 @TestSubject private final ClassTested classUnderTest = new ClassTested(); // 2 @Test public void addDocument() { collaborator.documentAdded("New Document"); // 3 replayAll(); // 4 classUnderTest.addDocument("New Document", "content"); // 5 verifyAll(); // 6 } } {% endhighlight %}

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!