--- layout: default title: Getting started comments: true locale: en ---
You have brand new class. Let's call it ClassTested.
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.
{% highlight xml %}Ok. Now addDocument should do stuff and then notify a dependency. Let's
call it Collaborator.
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:
Then the code fulfilling it:
{% highlight java %} 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 } } {% endhighlight %}And that's all you need to get you started. Some comments though:
EasyMockSupport is useful but not mandatory.
It allows to call replayAll instead of replay(mock1, mock2, ...) for instanceEasyMockRule) so you won't need a setter only used for testingdocumentAdded is called only once and receiving this exact parameter.
Any other call to our mock is a test failureFrom 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!