To EasyMock or to Mockito?

From time to time, I’ve found that mocking various dependencies can be helpful in testing behavior. Briefly, mocking an object allows you to fake its behavior so as to more fully isolate some other object depending on this behavior — the classic use case is that of mocking a data access layer, for example. In this case, testing some object that depends on a DAO object becomes a bit easier if you can mock out the DAO and thus not have to worry about an associated database, etc.

There are a plethora of mocking libraries out there (and in many cases, you can roll your own!) — one of my favorites for a long time has been EasyMock. This library has served its purpose for me when I’ve needed it; however, there’s a newer library on the block dubbed Mockito, whose hip description is best read word for word:

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn’t give you hangover because the tests are very readable and they produce clean verification errors.

Indeed, Mockito can mock classes just as easily as interfaces and in many ways, I’ve found its API to be much more natural and BDD-istic. Watch.

Each library is similar in spirit — for instance, when providing a stubbed implementation of a hip object, you request a mock of it and then you instruct the various frameworks on how to behave. For instance, with EasyMock, if you’d like to mock an instance of a Feed class (don’t worry too much about this class, suffice it to say, it is used in a ScoreBoard class, which is the class under test), you can do it like so:

scenario "using easy mock", {
  given "a mocked instance of feed", {
    feed = createMock(Feed.class)
    expect(feed.allScores()).andReturn( [new FootballGame(
        "Cleveland Browns", 20, "San Diego Chargers", 3)] as FootballGame[]
    )

    replay(feed);

  }
  then "things should work normally", {
    scoreBoard = new ScoreBoard(feed,
            new FootballGame("Washington Redskins", 0, "New York Giants", 45));

    games = scoreBoard.getAllScores()

    games[0].awayTeamScore().shouldBe 3
  }
}

As you can see in the EasyMock example (which is being driven via easyb), the Feed class’s allScores method is stubbed — in this case, a fake score is created (rather than say, retrieved from a live scoring system located on another server, for instance). Note how with EasyMock, the fluent interface-like API reads expect and return. With EasyMock, things get started via the replay method — as you can see, later in the scenario, this behavior is validated, thus demonstrating the mock.

EasyMock is definitely easy; however, watch the same example play out with Mockito:


scenario "using mockito", {
  given "a mocked instance of feed", {
    feed2 = mock(Feed.class)
    when(feed2.allScores()).thenReturn([new FootballGame(
       "Cleveland Browns", 20, "San Diego Chargers", 3)] as FootballGame[]
    )
  }
  then "things should work normally", {
    scoreBoard = new ScoreBoard(feed2,
            new FootballGame("Washington Redskins", 0, "New York Giants", 45));

    games = scoreBoard.getAllScores()

    games[0].awayTeamScore().shouldBe 3
  }
}

On the surface, things look to be the same, however, if it’s your bag and you look closely, you’ll see that Mockito’s API reads nicer: when then return — this is quite BDD-like, no? Plus, Mockito doesn’t require a replay-like call. Thus, to me, Mockito is a bit cleaner — it certainly complements easyb stories and scenarios with its when and thenReturn API calls.

While I’m only scratching the surface of features available in both libraries, Mockito’s API is more in tuned with my way of thinking — can you dig it, man?

Post to Twitter

Related odds and ends
 

9 Responses to “To EasyMock or to Mockito?”

  1. on 02 Dec 2009 at 3:35 am Chris Cantu

    Hey Andrew, great blog post. I am curious to know if you used Mockito inside a grails environment. I did a quick Google search and didn’t turn up much.

  2. on 02 Dec 2009 at 9:46 am Richard Paul

    Mockito takes it even further with its BDDMockito class. It basically aliases the ‘when thenReturn’ to ‘given willReturn’ so that you don’t have to use the when keyword in your given block.

    More details here:
    http://www.rapaul.com/2009/08/09/bddmockito-eclipse/
    http://mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/BDDMockito.html


  3. [...] This post was mentioned on Twitter by thediscoblog, Vinny Carpenter. Vinny Carpenter said: The Disco Blog » Blog Archive » To EasyMock or to Mockito? http://ff.im/-clZEp [...]

  4. on 03 Dec 2009 at 7:42 pm Christopher Bartling

    I much prefer mockito over EasyMock. Has great support for annotations:

    @Mock
    private PersonDao mockPersonDao;

    … // More mocks if need be

    @Before
    public void doBeforeEachTest() {
    MockitoAnnotations.initMocks(this);
    }

    I’ve also found the messages when something bad happens to be much more succinct and readable than EasyMocks. Just a nice evolution from the EasyMock stuff.

    – chris –


  5. [...] The Disco Blog » Blog Archive » To EasyMock or to Mockito? – While I’m only scratching the surface of features available in both libraries, Mockito’s API is more in tuned with my way of thinking [...]

  6. on 22 Dec 2009 at 1:54 pm Johannes Wiklund

    I have a serious problem with your scenario… I can’t believe you gave the Redskins a ZERO :-)

    Are you MOCKing them???

    Other than that, your logic looks flawless!

    Johannes

  7. on 22 Dec 2009 at 4:47 pm Andy

    Johannes — indeed, I guess the Redskins did actually get 12 points — but I couldn’t see the future all that well when I created this post!

  8. on 23 Dec 2009 at 4:51 am James Lorenzen

    I prefer an even simpler approach using Groovy’s metaClass or as keyword to Mock out method calls. In my experience it’s the simplest and most readable. You can typically mock a call out in 1 line. See http://jlorenzen.blogspot.com/2009/04/mock-testing-with-groovy.html.

  9. on 28 Dec 2009 at 6:50 pm faenvie

    do not forget gmock.org, which is a mock-library
    you really should consider to use, if you are
    free and willing to write your test-code in groovy.