What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?
14 Answers
I've had good success using Mockito.
When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).
I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.
Here's an (abridged) example from the Mockito homepage:
import static org.mockito.Mockito.*;
List mockedList = mock(List.class);
mockedList.clear();
verify(mockedList).clear();
It doesn't get much simpler than that.
The only major downside I can think of is that it won't mock static methods.

- 6,079
- 3
- 38
- 46

- 5,504
- 2
- 31
- 32
-
15Beautiful. For static methods, simply combine Mockito with JMockit and there is practically no class too "legacy" for you to be able to test. – Epaga Mar 13 '09 at 14:26
-
6I love how when you try to do something you shouldn't (e.g. create mocks inline), you get a very clear explanation of what you did wrong in the exception message. – ripper234 Jun 27 '09 at 12:00
-
+1 for Mockito. Even though nowhere mentioned, it seems heavily inspired by Ruby's Mocha framework (which is great). – mxk Feb 05 '10 at 21:26
-
1The only think I don't like about mockito is that you cannot use it for android, other than that is a great framework – MexicanHacker Mar 19 '10 at 18:28
-
3For me, absolutely. I would still recommend it unconditionally. Of course, if you find another framework that better meets your needs, mention it in another answer and see what votes it gets and what kinds of comments it receives. – Brian Laframboise Mar 02 '11 at 15:24
-
2@MexicanHacker why couldn't you use it for Android? I'm using it right now, with Robolectric. – Ilkka Mar 19 '11 at 18:57
-
@Ilkka It's hard to remember now, the problem was in March 2010, at that moment mockito was not able to mock finals, which is something you'll find a lot in Dalvik, here is more info: https://sites.google.com/site/androiddevtesting/ – MexicanHacker Mar 22 '11 at 00:25
-
1I´ve experienced with EasyMock and I find it quite easy to use... so if mockito is easier I guess it is REALLY easy and it deserves a try. – Jaime Hablutzel Jun 25 '11 at 01:07
-
1@MexicanHacker, PowerMock extends Mockito so you can run Android tests natively on the host PC. – Jeff Axelrod Jul 14 '11 at 18:09
-
2I'm using Mockito and loving it!! Great documentation too (so rare to find documentation of this quality, good job from the authors), which is so important for us to use stuff without having to dig into the framework's code!!! – Renato Mar 08 '12 at 07:37
-
As Jan Kronquist says in his answer, you can use PowerMock to extend Mockito if you need to mock static methods. – SamStephens Mar 20 '13 at 18:49
-
@MexicanHacker looks like there's been some work in Mockito recently to support Android. I don't know anything about it, but it's mentioned here: http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Mockito.html#28 – SamStephens Mar 20 '13 at 18:51
I am the creator of PowerMock so obviously I must recommend that! :-)
PowerMock extends both EasyMock and Mockito with the ability to mock static methods, final and even private methods. The EasyMock support is complete, but the Mockito plugin needs some more work. We are planning to add JMock support as well.
PowerMock is not intended to replace other frameworks, rather it can be used in the tricky situations when other frameworks does't allow mocking. PowerMock also contains other useful features such as suppressing static initializers and constructors.

- 2,793
- 25
- 20
-
Powermock is essential for unit testing Android applications using native Java on the host PC (avoiding using the slow emulator) – Jeff Axelrod Jul 14 '11 at 18:08
-
@Jan only issue is PowerMock is incompatible when using Robolectric though :-( I want to do @RunWith(PowerMockRunner.class) AND @RunWith(RobolectricTestRunner.class) – Blundell Oct 22 '11 at 00:29
-
-
PowerMock really is awesome. I really love static singletons to access everything, and this makes that possible to test. – Ian Macalinao Mar 17 '12 at 08:42
-
Caveat: some things like mocking final methods are only possible in Powermock for EasyMock and not for Mockito. It's a bit of a gotcha when you don't use it that frequently. I was wondering why something wasn't working then I realised it's only listed under the Easymock section of the doco. – trafalmadorian Dec 04 '13 at 23:57
The JMockit project site contains plenty of comparative information for current mocking toolkits.
In particular, check out the feature comparison matrix, which covers EasyMock, jMock, Mockito, Unitils Mock, PowerMock, and of course JMockit. I try to keep it accurate and up-to-date, as much as possible.

- 16,171
- 2
- 50
- 63
-
1I am impressed by JMockit, it has a steeper learning curve, but it has very good documentation for years, and it can mock anything. I started with Mockito, which was easy to learn, but I regularly met problems which I could not solve with it. On the other hand I cannot even imagine what is impossible with JMockit. – Hontvári Levente Apr 16 '15 at 15:39
I've been having success with JMockit.
It's pretty new, and so it's a bit raw and under-documented. It uses ASM to dynamically redefine the class bytecode, so it can mock out all methods including static, private, constructors, and static initializers. For example:
import mockit.Mockit;
...
Mockit.redefineMethods(MyClassWithStaticInit.class,
MyReplacementClass.class);
...
class MyReplacementClass {
public void $init() {...} // replace default constructor
public static void $clinit{...} // replace static initializer
public static void myStatic{...} // replace static method
// etc...
}
It has an Expectations interface allowing record/playback scenarios as well:
import mockit.Expectations;
import org.testng.annotations.Test;
public class ExpecationsTest {
private MyClass obj;
@Test
public void testFoo() {
new Expectations(true) {
MyClass c;
{
obj = c;
invokeReturning(c.getFoo("foo", false), "bas");
}
};
assert "bas".equals(obj.getFoo("foo", false));
Expectations.assertSatisfied();
}
public static class MyClass {
public String getFoo(String str, boolean bool) {
if (bool) {
return "foo";
} else {
return "bar";
}
}
}
}
The downside is that it requires Java 5/6.

- 16,038
- 10
- 74
- 104

- 3,280
- 4
- 25
- 30
-
-
7Just an update: the JMockit project moved to http://code.google.com/p/jmockit. It has evolved A LOT since this post (and still is evolving), and now has extensive documentation. – Rogério Dec 27 '09 at 01:18
-
JMockit has moved again. It's now available at Github. http://jmockit.github.io – Ravi K Thapliyal Feb 08 '15 at 14:55
You could also have a look at testing using Groovy. In Groovy you can easily mock Java interfaces using the 'as' operator:
def request = [isUserInRole: { roleName -> roleName == "testRole"}] as HttpServletRequest
Apart from this basic functionality Groovy offers a lot more on the mocking front, including the powerful MockFor
and StubFor
classes.

- 6,323
- 2
- 22
- 26

- 1,980
- 1
- 16
- 22
I started using mocks with EasyMock. Easy enough to understand, but the replay step was kinda annoying. Mockito removes this, also has a cleaner syntax as it looks like readability was one of its primary goals. I cannot stress enough how important this is, since most of developers will spend their time reading and maintaining existing code, not creating it.
Another nice thing is that interfaces and implementation classes are handled in the same way, unlike in EasyMock where still you need to remember (and check) to use an EasyMock Class Extension.
I've taken a quick look at JMockit recently, and while the laundry list of features is pretty comprehensive, I think the price of this is legibility of resulting code, and having to write more.
For me, Mockito hits the sweet spot, being easy to write and read, and dealing with majority of the situations most code will require. Using Mockito with PowerMock would be my choice.
One thing to consider is that the tool you would choose if you were developing by yourself, or in a small tight-knit team, might not be the best to get for a large company with developers of varying skill levels. Readability, ease of use and simplicity would need more consideration in the latter case. No sense in getting the ultimate mocking framework if a lot of people end up not using it or not maintaining the tests.

- 10,639
- 3
- 49
- 62

- 1,660
- 1
- 15
- 21
-
1+1 This answer need more upvotes. One should share what they actually liked or not about the framework. Just "I used this.. and I liked it!" is one of the reasons why such good questions get closed on SO. – Ravi K Thapliyal Feb 08 '15 at 14:52
We are heavily using EasyMock and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.

- 19,249
- 13
- 42
- 53
-
1In my question, I was more looking for what you like and dislike about a mock framework. I can find the documentation and read all about it - I want to know what the people who have used it think of it. – Josh Brown Sep 07 '08 at 23:44
-
I used JMock early. I've tried Mockito at my last project and liked it. More concise, more cleaner. PowerMock covers all needs which are absent in Mockito, such as mocking a static code, mocking an instance creation, mocking final classes and methods. So I have all I need to perform my work.

- 89
- 1
- 1
I like JMock because you are able to set up expectations. This is totally different from checking if a method was called found in some mock libraries. Using JMock you can write very sophisticated expectations. See the jmock cheat-sheat.

- 52,385
- 10
- 54
- 80

- 9,737
- 16
- 56
- 70
Yes, Mockito is a great framework. I use it together with hamcrest and Google guice to setup my tests.

- 2,782
- 1
- 19
- 18
The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see ScalaCheck and the Reductio framework included in the Functional Java library. With automated specification-based testing frameworks, you supply a specification of the method under test (a property about it that should be true) and the framework generates tests as well as mock objects, automatically.
For example, the following property tests the Math.sqrt method to see if the square root of any positive number n squared is equal to n.
val propSqrt = forAll { (n: Int) => (n >= 0) ==> scala.Math.sqrt(n*n) == n }
When you call propSqrt.check()
, ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.
Even though ScalaCheck is written in Scala, and requires the Scala Compiler, it's easy to test Java code with it. The Reductio framework in Functional Java is a pure Java implementation of the same concepts.

- 2,092
- 5
- 33
- 55

- 34,834
- 8
- 106
- 155
Mockito also provides the option of stubbing methods, matching arguments (like anyInt() and anyString()), verifying the number of invocations (times(3), atLeastOnce(), never()), and more.
I've also found that Mockito is simple and clean.
One thing I don't like about Mockito is that you can't stub static methods.

- 1
- 1

- 52,385
- 10
- 54
- 80
-
This answer is inaccurate. You are not limited to interfaces with jMock. You can mock concrete classes with the ClassImposteriser. – Teflon Ted Sep 12 '08 at 02:59
-
-
For something a little different, you could use JRuby and Mocha which are combined in JtestR to write tests for your Java code in expressive and succinct Ruby. There are some useful mocking examples with JtestR here. One advantage of this approach is that mocking concrete classes is very straightforward.

- 3,472
- 19
- 17
I started using mocks through JMock, but eventually transitioned to use EasyMock. EasyMock was just that, --easier-- and provided a syntax that felt more natural. I haven't switched since.

- 1,105
- 1
- 11
- 17