--- layout: default title: Getting started comments: true locale: en ---
Add EasyMock dependency to your POM file.
{% highlight xml %}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:
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!