November 29, 2007

Introduction to jMockit

Mockobjects plays a vital role in unit testing and TDD. They are not only used for unit testing but also helpful in integration testing.

There are various tools available for creating mockobjects. For Java
EasyMock and jMock are mostly used. Both are based on java.lang.reflect.Proxy. Because of that EasyMock and jMock have their own constraints.

  • They are actually pattern specific. Each of these tools requires an interface to be implemented and if there is no interface is present, create the same. This way developer can refactor their design. But most of the time developers are not allowed to change the design of project or they are working on Legacy Code (like me).
  • These tools have rich APIs to express expectations that has to be verified when objects are called. But most of the time, checks written as EasyMock/jMock expectation instead of using JUnit's already available assertion methods.
  • No static method for which a mock implementation might be needed can be used.
  • All mocked methods need to be public for mock classes that implement an interface, or at least protected for mock sub classes.

    To solve these problems jMockit comes into picture. It provides a facility to create mockobject without any design restriction. jMockit is based on java.lang.instrument package. This package is only available with Java 5 or more.

    jMockit can be applicable for any design. Developer can test their code without worrying about design. Test writer can also keep using testing framework assertion rather then tool specific assertion.


    1. I also use JMockit beside EasyMock and jMock for creating mock objects in projects, especially


      Stephan Schmidt ::
      Reposita Open Source - Monitor your software development
      Blog at - No signal. No noise.

    2. "But most of the time developers are not allowed to change the design of project".

      You're basically saying that most of the time developers are not allowed to do their job to an appropriate professional standard. That is just not true in my experience.

      If you can't change the design, what's the point of testing at all? What do you do when the tests fail?

    3. anonymous- I am saying to unit test code, client does not allow us to introduce interfaces.
      This is sad but I have to do that. I mostly work on Banking Application and they are made up of large chunk of Legacy Code.
      Unit test is not required by client but I do it as a hobby.
      Thanks for your comment.

    4. hi, jMockit is a truly powerful tool, but don't let us be fooled - even if thanks to jmockit we are able to test some crappy code it doesn't mean we are allowed to write such code ! :)

      BTW. I wrote a serie of posts dedicated to unit testing of some "untestable code" and jmockit is one of the solutions I describe there. Maybe you'll find it interesting. See here:

      Tomek Kaczanowski