<p>What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?</p>

[{'answer_id': 23048, 'author': 'Brian Laframboise', 'author_id': 1557, 'author_profile': 'https://Stackoverflow.com/users/1557', 'pm_score': 9, 'selected': True, 'text': '<p>I\'ve had good success using <a href="https://github.com/mockito/mockito" rel="noreferrer">Mockito</a>.</p>\n\n<p>When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that\'s just me).</p>\n\n<p>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.</p>\n\n<p>Here\'s an (abridged) example from the Mockito homepage:</p>\n\n<pre><code>import static org.mockito.Mockito.*;\n\nList mockedList = mock(List.class);\nmockedList.clear();\nverify(mockedList).clear();\n</code></pre>\n\n<p>It doesn\'t get much simpler than that.</p>\n\n<p>The only major downside I can think of is that it won\'t mock static methods.</p>\n'}, {'answer_id': 23295, 'author': 'dlinsin', 'author_id': 198, 'author_profile': 'https://Stackoverflow.com/users/198', 'pm_score': 4, 'selected': False, 'text': '<p>We are heavily using <a href="http://easymock.org" rel="noreferrer">EasyMock</a> 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.</p>\n'}, {'answer_id': 27786, 'author': 'Mike Furtak', 'author_id': 3005, 'author_profile': 'https://Stackoverflow.com/users/3005', 'pm_score': 1, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 28015, 'author': 'Josh Brown', 'author_id': 2030, 'author_profile': 'https://Stackoverflow.com/users/2030', 'pm_score': 2, 'selected': False, 'text': '<p>Mockito also provides the option of stubbing methods, matching arguments (like anyInt() and anyString()), verifying the number of invocations (times(3), atLeastOnce(), never()), <a href="http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html" rel="nofollow noreferrer">and more</a>.</p>\n\n<p>I\'ve also found that Mockito is <a href="https://stackoverflow.com/questions/22697/whats-the-best-mock-framework-for-java#23048">simple and clean</a>.</p>\n\n<p>One thing I don\'t like about Mockito is that you <a href="http://code.google.com/p/mockito/wiki/FAQ" rel="nofollow noreferrer">can\'t stub static methods</a>.</p>\n'}, {'answer_id': 37028, 'author': 'Bartosz Bierkowski', 'author_id': 3666, 'author_profile': 'https://Stackoverflow.com/users/3666', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, Mockito is a great framework. I use it together with <a href="http://code.google.com/p/hamcrest/" rel="noreferrer">hamcrest</a> and <a href="http://code.google.com/p/google-guice/" rel="noreferrer">Google guice</a> to setup my tests.</p>\n'}, {'answer_id': 92998, 'author': 'p3t0r', 'author_id': 16685, 'author_profile': 'https://Stackoverflow.com/users/16685', 'pm_score': 4, 'selected': False, 'text': '<p>You could also have a look at testing using Groovy. In Groovy you can easily mock Java interfaces using the \'as\' operator:</p>\n\n<pre><code>def request = [isUserInRole: { roleName -&gt; roleName == "testRole"}] as HttpServletRequest \n</code></pre>\n\n<p>Apart from this basic functionality Groovy offers a lot more on the mocking front, including the powerful <code>MockFor</code> and <code>StubFor</code> classes.</p>\n\n<p><a href="http://docs.codehaus.org/display/GROOVY/Groovy+Mocks" rel="nofollow noreferrer">http://docs.codehaus.org/display/GROOVY/Groovy+Mocks</a></p>\n'}, {'answer_id': 93675, 'author': 'Kris Pruden', 'author_id': 16977, 'author_profile': 'https://Stackoverflow.com/users/16977', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve been having success with <a href="http://jmockit.github.io/index.html" rel="noreferrer">JMockit</a>.</p>\n\n<p>It\'s pretty new, and so it\'s a bit raw and under-documented.  It uses <a href="http://asm.objectweb.org/index.html" rel="noreferrer">ASM</a> to dynamically redefine the class bytecode, so it can mock out all methods including static, private, constructors, and static initializers.  For example:</p>\n\n<pre><code>import mockit.Mockit;\n\n...\nMockit.redefineMethods(MyClassWithStaticInit.class,\n                       MyReplacementClass.class);\n...\nclass MyReplacementClass {\n  public void $init() {...} // replace default constructor\n  public static void $clinit{...} // replace static initializer\n  public static void myStatic{...} // replace static method\n  // etc...\n}\n</code></pre>\n\n<p>It has an Expectations interface allowing record/playback scenarios as well:</p>\n\n<pre><code>import mockit.Expectations;\nimport org.testng.annotations.Test;\n\npublic class ExpecationsTest {\n  private MyClass obj;\n\n  @Test\n  public void testFoo() {\n    new Expectations(true) {\n      MyClass c;\n      {\n        obj = c;\n        invokeReturning(c.getFoo("foo", false), "bas");\n      }\n    };\n\n    assert "bas".equals(obj.getFoo("foo", false));\n\n    Expectations.assertSatisfied();\n  }\n\n  public static class MyClass {\n    public String getFoo(String str, boolean bool) {\n      if (bool) {\n        return "foo";\n      } else {\n        return "bar";\n      }\n    }\n  }\n}\n</code></pre>\n\n<p>The downside is that it requires Java 5/6.</p>\n'}, {'answer_id': 382692, 'author': 'Andrea Francia', 'author_id': 36131, 'author_profile': 'https://Stackoverflow.com/users/36131', 'pm_score': 3, 'selected': False, 'text': '<p>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 <a href="http://www.jmock.org/cheat-sheet.html" rel="nofollow noreferrer">cheat-sheat</a>.</p>\n'}, {'answer_id': 488978, 'author': 'Jan Kronquist', 'author_id': 43935, 'author_profile': 'https://Stackoverflow.com/users/43935', 'pm_score': 6, 'selected': False, 'text': '<p>I am the creator of PowerMock so obviously I must recommend that! :-)</p>\n\n<p><a href="http://powermock.org" rel="noreferrer">PowerMock</a> extends both EasyMock and Mockito with the ability to <a href="http://code.google.com/p/powermock/wiki/MockStatic" rel="noreferrer">mock static methods</a>, 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. </p>\n\n<p>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 <a href="http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior" rel="noreferrer">suppressing static initializers</a> and constructors.</p>\n'}, {'answer_id': 489089, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 2, 'selected': False, 'text': '<p>The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see <a href="http://www.scalacheck.org/" rel="nofollow noreferrer">ScalaCheck</a> and the <a href="http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/test/package-summary.html" rel="nofollow noreferrer">Reductio</a> framework included in the <a href="http://functionaljava.org" rel="nofollow noreferrer">Functional Java</a> 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.</p>\n\n<p>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.</p>\n\n<pre><code>val propSqrt = forAll { (n: Int) =&gt; (n &gt;= 0) ==&gt; scala.Math.sqrt(n*n) == n }\n</code></pre>\n\n<p>When you call <code>propSqrt.check()</code>, ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.</p>\n\n<p>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.</p>\n'}, {'answer_id': 508379, 'author': 'James Mead', 'author_id': 2025138, 'author_profile': 'https://Stackoverflow.com/users/2025138', 'pm_score': 2, 'selected': False, 'text': '<p>For something a little different, you could use <a href="http://jruby.codehaus.org/" rel="nofollow noreferrer">JRuby</a> and <a href="http://mocha.rubyforge.org/" rel="nofollow noreferrer">Mocha</a> which are combined in <a href="http://docs.codehaus.org/display/JTESTR/Home" rel="nofollow noreferrer">JtestR</a> to write tests for your Java code in expressive and succinct Ruby. There are some useful mocking examples with JtestR <a href="http://docs.codehaus.org/display/JTESTR/Mocks" rel="nofollow noreferrer">here</a>. One advantage of this approach is that mocking concrete classes is very straightforward.</p>\n'}, {'answer_id': 1024869, 'author': 'Rogério', 'author_id': 2326914, 'author_profile': 'https://Stackoverflow.com/users/2326914', 'pm_score': 6, 'selected': False, 'text': '<p>The <a href="http://jmockit.org" rel="noreferrer">JMockit project site</a> contains plenty of comparative information for current mocking toolkits.</p>\n\n<p>In particular, check out the <strong><a href="http://jmockit.org/MockingToolkitComparisonMatrix.html" rel="noreferrer">feature comparison matrix</a></strong>, 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.</p>\n'}, {'answer_id': 2032739, 'author': 'Dmitry', 'author_id': 246969, 'author_profile': 'https://Stackoverflow.com/users/246969', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 6393609, 'author': 'trafalmadorian', 'author_id': 204255, 'author_profile': 'https://Stackoverflow.com/users/204255', 'pm_score': 4, 'selected': False, 'text': '<p>I started using mocks with <a href="http://easymock.org/" rel="noreferrer">EasyMock</a>. Easy enough to understand, but the replay step was kinda annoying. <a href="http://code.google.com/p/mockito/" rel="noreferrer" title="Mockito">Mockito</a> 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. </p>\n\n<p>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.</p>\n\n<p>I\'ve taken a quick look at <a href="http://jmockit.org/" rel="noreferrer" title="JMockit">JMockit</a> 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. </p>\n\n<p>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 <a href="http://code.google.com/p/mockito/" rel="noreferrer" title="Mockito">Mockito</a> with <a href="http://code.google.com/p/powermock/" rel="noreferrer">PowerMock</a> would be my choice.</p>\n\n<p>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. </p>\n'}]
['https://Stackoverflow.com/questions/22697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2030/']