by Jean Tessier
This document shows how to do common mocking tasks in Java using both jMock, EasyMock, and Mockito.
Throughout, I use the terminology defined by Gerard Meszaros in his book xUnit Test Patterns.
All example were tested with JUnit 4, jMock 2.13, EasyMock 5.2.0, and Mockito 5.12.0 using Java 21.
Alternative versions: JUnit 4, JUnit 5
I like jMock a lot more than I like EasyMock. The DSL for specifying expectations in jMock takes some getting used to, but it is more expressive than the one in EasyMock. And while I don't like anonymous inner classes, I like static imports even less. :-)
A Slant article titled "What are the best mock frameworks for Java", in 2020, had a top three of:
- Mockito
- JMockIt
- EasyMock (a very distant third)
There has been very little development, of late, on either JMock or EasyMock. In the meantime, Mockito has been on a tear. I don't know JMockIt.
For my part, my new favorite testing framework on the JVM is Spock. It uses Groovy to write the tests, which have a much more BDD feel to them. It's support for mocking is also top-notch.
Mocking allows you to isolate a class or method and test it in isolation. You replace all of its collaborator with mocks that essentially simulate the normal environment of the SUT (System Under Test). Mocks replace the SUT's DOCs (Depended-On Components) and give you fine control on how the SUT interacts with its environment and what messages it gets back from it.
jMock (jmock.org)
jMock focuses on explicitly specifying the behavior of the mocks using a specialized DSL (Domain-Specific Language) embedded in the Java code. The notation takes some getting used to, but it makes the specification of behavior stand out in the test code.
EasyMock (easymock.org)
EasyMock takes a record/replay approach. You first train the mock by making the expected method calls on it yourself. You then switch the mock into replay-mode before exercising the SUT. Specifying the behavior is just regular method calls on a typed Java object.
Mockito (mockito.org)
Mockito takes a different approach. Whereas jMock and EasyMock try to specify the behavior fully beforehand, Mockito simply records everything indiscriminately and then lets you verify that what you wanted actually happened. Instead of a large specification section at the front of the test, you have a large verification section at the end of it. Strictly speaking, Mockito uses test spies rather than mocks to simulate the DOCs.
Once I figure out how to do a decent three-column layout with code samples in MarkDown, I will port the remainder of the article here.
Date | Edit |
---|---|
2008-05-29 | First draft. |
2008-11-20 | Last substantial edit. |
2020-04-29 | Making sure it all still works with the latest versions. |