Mockito

I’m a mockist but existing mock frameworks just don’t appeal to me. They spoil my TDD experience. They harm code readability. I needed something better. That’s why I came up with Mockito.

Syntax

Here is a what I think about mocking syntax:

  • Let’s keep it simple: interactions are method calls. There is no point in building sophisticated mocking language for method calls in Java. There is already a language for that. It’s called Java.
  • The less DSL the better. Interactions are just method calls. Method calls are simple, DSL is complex.
  • No Strings for methods. I spent more time reading code than writing it. Therefore I want the code to be readable. String literals pretending to be methods cannot compete with actual method calls. Even IDEs decorate literals differently so my mind will always adopt the real method call quicker than any literal trying to impersonate a method.
  • No anonymous inner classes. They bring more indentation, more curly brackets, more code, more noise. Did I mention that I spent more time reading code?
  • Painless refactoring. Renaming a method should not break my tests.

That’s why I really like the syntax of EasyMock.

Long journey from EasyMock to Mockito

I was brought up on EasyMock. Normal kids got milk I got classes to test. Over the years on different projects I saw idyllic world of hand crafted stubs being overthrown by EasyMocks. On other project, jmock was doing fine until he got a Chuck’s roundhouse kick to the face by EasyMock. Finally, I saw resentment to EasyMock and triumphatic comeback of hand crafted stubs… Sometimes the resentment to EasyMock was a bit naive (“My class has 10 dependencies and is difficult to test. Therefore EasyMock sucks”). Sometimes it was clearly righteous…

Here is what I wanted to achieve with Mockito so that it suits me better in test-driving code the way I like:

tdd

Focused testing. Should let me focus test methods on specific behavior/interaction. Should minimize distractions like expecting/recording irrelevant interactions.

Separation of stubbing and verification. Should let me code in line with intuition: stub before execution, selectively verify interactions afterwards. I don’t want any verification-related code before execution.

Explicit language. Verification and stubbing code should be easy to discern, should distinguish from ordinary method calls / from any supporting code / assertions.

Simple stubbing model. Should bring the simplicity of good old hand crafted stubs without the burden of actually implementing a class. Rather than verifying stubs I want to focus on testing if stubbed value is used correctly.

Only one type of mock, one way of creating mocks. So that it’s easy to share setup.

No framework-supporting code. No record(), replay() methods, no alien control/context objects. These don’t bring any value to the game.

Slim API. So that anyone can use it efficiently and produce clean code. API should push back if someone is trying to do something too smart: if the class is difficult to test – refactor the class.

Explicit errors. Verification errors should always point stack trace to failed interaction. I want to click on first stack element and navigate to failed interaction.

Clean stack trace. Part of TDDing is reading stack traces. It’s Red-Green-Refactor after all – I’ve got stack trace when it’s red. Stack trace should always be clean and hide irrelevant internals of a library. Although modern IDE can help here, I’d rather not depend on IDE neither on competence in using IDE…

road split

EasyMock is a decent piece of software, credits go to kick-ass people who wrote it. Initial hacks on Mockito were done on top of the EasyMock code but since then I rewrote most of the codebase. Enjoy.

About these ads

52 Responses to Mockito

  1. […] disproportionately upset I was when Ted Wragg died, about how disproportionately excited I am about yet another mocking framework, or how simply joyful Super Mario Galaxy is; so this is now the place for such […]

  2. Nathan McDonald says:

    Just tried out Mockito, was skeptical at first but already I love it. I’m a big fan of EasyMock and think the mocking syntax is great, but the expect/verify etc… can lead to some really bloated tests which are hard to read.

    Mockito meant I could combine the expect and verify lines. Puts verification definition AFTER method call as well, which is more intuitive. No need for the replay or reset calls. So 5 lines becomes 2. Since 1 is the actual method invocation, I would say the mock specific code is now 1 line instead of 4!

    Once this was cleaned up, realised i was checking my stubbed return value. Not much value in that, but was much easier to see I was doing that (unnecessary) step once I’d removed the other clutter. Got rid of the return value check so now I have a much cleaner and readable test.

    Once again awesome tool.

  3. szczepiq says:

    Thanks a lot for your feedback!

  4. SkullCruncha says:

    Anyone who has hand coded their mock classes should look into this tool, especially when you have had to create unneccesary interfaces so you could provide so you could provide mock implementations for testing.

    This tool rocks.

  5. […] reading a lot of noise from fellow ThoughtWorkers in the recent past about Mockito. I decided to give a yet another mock framework a […]

  6. Nice introduction. I have no idea what mocking is, yet I’m convinced on the strings. A great point. In fact, I’m convinced by your arguments by the tone of the arguments. It sounds the way I sound when I’m struggling to use something that has made a simple idea complex.

    Okay, I have some idea what mocking is, but I’ve never used it. The mocking libraries always looked to complex for me to invest time. It always seemed like I’d be writing at least a quarter of the library I’m trying to test in mock objects. I would rather design the library to be testable or else just write fewer tests, spend more time on code reads and assertions.

    Yeah, I said it. Write fewer tests. As something gets difficult, less of it gets done.

    Anyway, I wanted to suggest a few changes to your intro…

    I don’t know was a DSL is. You should spell out algorithms in an introduction. I didn’t know what TDD was at first, but it came to me.

    I get the feeling if I knew what stubbing and verification were, that post would be a great introduction not only to mockito, but to TDD as well.

    This sentence: “It’s Red-Green-Refactor after all – I’ve got stack trace when it’s red. ” is pretty much the best description of TDD I’ve read. Two additional parenthetical sentences, and I’d probably know the 20% that does the 80%.

    I wanted to suggest these changes, because this is a great sales letter. I wish every open source project had a nice, friendly description of motivations like this one.

    That’s about it. I’m going to look at mockito. Thanks for describing your intent clearly.

  7. Adam Hardy says:

    I’d love mocking to be easier, I’m going to give this a go.

    Anyone using maven, it’s found on the repo as org.mockito mockito-all

  8. Adam Hardy says:

    Hold on a moment, I take that back – that package info was cached and the package is no longer there. Szczepan, what’s the situation, please?

  9. szczepiq says:

    The jar is there: http://repo1.maven.org/maven2/org/mockito/mockito-all/1.2/. Also, if you have questions, you can always drop an email to our mailing list

  10. John Smith says:

    Love your mock library. I never could get used to the ugly syntax of JMock. Mockito is simple and intuitive. Great job!! I started using it on my project, the first few unit tests have been really easy and intuitive.

  11. […] can read more about how Mockito came about on the author’s blog. I highly recommend checking it out! Share and Enjoy: These icons link to social bookmarking […]

  12. Ken Ko says:

    I’ve previously used RMock, and I’m looking as to whether we should switch the Mockito in our next project. Do you have a comparison of mock libraries? It seems that both libraries offer the same level of functionality, but mockito syntax seems a little cleaner. Any thoughts?

  13. szczepiq says:

    I haven’t used RMock in anger – I always considered EasyMock and jMock the best mocking frameworks in the java world. I put a quick RMock vs Mockito comparison here. Feel free to give feedback – after all you’re an RMock user.

  14. Anay Kamat says:

    After trying to use other mocking tools for java, I finally opted for Mockito to create mocks in our unit tests. We have java code as well as server code. Due to mockito, our junit tests are more readable than nunit tests (where all expectations settings and ReplayAll exists).

  15. […] I wrote Mockito because I needed a simple mocking tool that didn’t get in the way and gave readable code. In fact, the syntactic noise in jMock really helps to bring this out, whereas it’s easy for it […]

  16. Very impressed. Was just starting a new project and using jmock, and someone mentioned mockito so i thought i’d give it go.

    Functionally it appears to do the same thing as other mock libraries (mock stuff!)… however the clarity of the api is a pleasure to use. The readability of the tests produced is… err very readable.

    Nice work. Cheers.

  17. Steve says:

    Last evening I used Mockito for the first time, after a coworker recommended it. I’m sold! I haven’t used other mocking frameworks, so the only comparison I have is against my manually mocked interfaces and classes.

    Comparing the dozens (hundreds?) of setup lines, hacks, null method implementations I used to need to mock out legacy system and 3rd party interfaces and services, the 12 lines of Mockito I needed to mock out a set of domain objects and a few services are a joy to behold.

    I found four bugs in the two classes I was playing with, and I think that this can be attributed directly to the ease with which I was able to create the test cases in the first place.

    Nice job, guys!

    I’m now somewhat annoyed with myself for not finding Mockito earlier.

  18. Junho says:

    Great job on Mockito. I’ve tried several other mock frameworks out there but have decided to stick with Mockito because I have the easiest time doing what I need to do–test my code.

  19. Great tool, thanks for sharing it with us.

  20. Foo Barolo says:

    Thank you for creating this gem. The fact that I have used jmock for the last time brings joy to my meager existence. I wish more frameworks were so well-written.

  21. Will says:

    On my last project one of my developers suggested mockito, I was skeptical of learning another mocking framework given the pain I had to learn jMock. But as a good tech lead I listened, used, and now I’m sold on Mockito. It was very easy to create tests that I could follow.

  22. Eric Kramer says:

    Awesome! This *exactly* what I was looking for. As I surveyed the other libraries I thought, wow, this seems like a LOT of work compared to just creating manual stubs myself. THEN I found your library and this manifesto. Nice work!

  23. Joe says:

    This makes testing enjoyable. I can focus on the flow of the system rather than on annoying little odds and ends. Hats off to you.

  24. […] Faber, the author of Mockito, has a few things to say on why his tool is well done and conceptually right for unit-testing. I will just focus on a few […]

  25. Adam says:

    If you’re not using JMock then you’re not doing it right.

    http://www.jmock.org

  26. Jared says:

    These are truly fantastic ideas in concerning blogging.
    You have touched some nice points here. Any way keep up wrinting.

  27. Justin says:

    One of the things I love the most about Mockito is its type safety. We used JMock and there is no type safety in it, so runtime errors in JMock turn into compile time errors in Mockito.

  28. storify.com says:

    Wow, this piece of writing is nice, my sister is
    analyzing these things, so I am going to tell
    her.

  29. If some one desires to be updated with most up-to-date technologies afterward he must be go to see this web site
    and be up to date every day.

  30. Jeremy says:

    SAY THANK YOU for bringing this to my eyes, our family will
    benefit a lot.

  31. link says:

    I need to to thank you for this wonderful read!!
    I absolutely enjoyed every bit of it. I’ve got you bookmarked to check out new stuff you post…

  32. szampony says:

    Howdy fantastic blog! Does running a blog like this require a great deal of work?
    I have virtually no understanding of computer programming however I
    was hoping to start my own blog soon. Anyway,
    if you have any suggestions or tips for new blog owners please share.
    I understand this is off topic however I just needed to ask.
    Thanks a lot!

  33. Pavel says:

    That’s a very good Api. You save from one to two method calls for each mock, which is quite a lot. Also exilicpt verification of mocks is something you would want to have available in some cases.However you should set up a Pear channel to distribute it, so that Phake can easily be installed along with PHPUnit in development machines.

  34. click here says:

    We need more insights like this in this thread.

  35. […] Inicialmente se basa en la sintaxis y funcionalidad de EasyMock, pero posteriormente pasa casi a reescribirlo por […]

  36. pendrive says:

    Whеn I originally commented I clicked the “Notify me when new comments are added”
    chеckbolx and now each tіme a comment iѕ added I get four emails with thеe samе comment.
    Is there any wаy yyou cсan remove me fгom that service?
    Appreciate it!

  37. […] for this – multiple ifs in the serializer or even ConditionalSerialization.The issue is that I spend most of my time reading code, and I like meaningful class names. We need to find something […]

  38. mobile games says:

    You can certainly see your enthusiasm in the
    work you write. The world hopes for even more passionate writers like you
    who aren’t afraid to say how they believe. At all times follow your heart.

  39. Wasze Seriale Twoje filmy i seriale online za online za darmo.
    Premiery zapowiedzi filmowe. Nowości kinowe i wiele innych.

  40. Howdy! I know this iss somewhat off topic but I wass wondering
    which blog platrform are you using for this site?
    I’m getting fed up of WordPress because I’ve had issues with hackers andd I’m looking att
    alternatives for another platform. I would be awesome
    if you could pooint me in the direction of a good platform.

  41. Jestem naprawdę zadowolony polecam

  42. Nader szałowy post, badawcze teksty zalecam wszystkim lekturę

  43. ivr says:

    Wielce fajowy post, interesujące wpisy zalecam wszystkim lekturę

  44. swingers says:

    I used to be recommended this blog through my cousin. I am not positive whether or not this post
    is written by him as no one else realize such specific about my difficulty.
    You’re incredible! Thanks!

  45. Każdy z nas zetknął się z faktem, polecam zapoznanie się z faktem.

  46. Hello very cool blog!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your
    web site and take the feeds also? I am happy to find numerous useful info right here in the put up, we need develop extra techniques
    on this regard, thank you for sharing. . . . .
    .

  47. Niice post. I learn something new and challenging on sites
    I stumbleupon every day. It’s always useful to read through articles from other weiters and use a little something from other web sites.

  48. how to measure dress size diagram

    Mockito | monkey island

  49. swimwear for women large breasts

    Mockito | monkey island

  50. place zabaw says:

    Strona świadczy o dobrych zagadnieniach, zapraszam
    do rozmowy

  51. Gaston says:

    Wooden shelves are more aesthetically pleasing than metal and are a nice alternative in an office environment where you want everything to
    look nice and business-like. There are a large number of different types of storage.
    These are items that are often stolen and sold at a very fast pace.

Follow

Get every new post delivered to your Inbox.

Join 42 other followers

%d bloggers like this: