What are mock objects in Java?

I like to know what mock objects are in Java. Why do we create them and what are their uses?


A Mock object is something used for unit testing. If you have an object whose methods you want to test, and those methods depend on some other object, you create a mock of the dependency rather than an actual instance of that dependency. This allows you to test your object in isolation.

Common Java frameworks for creating mock objects include JMock and EasyMock. They generally allow you to create mock objects whose behavior you can define, so you know exactly what to expect (as far as return values and side effects) when you call methods on the mock object.

As an example, one common use case might be in an MVC application, where you have a DAO layer (data access objects) and a Controller that performs business logic. If you'd like to unit test the controller, and the controller has a dependency on a DAO, you can make a mock of the DAO that will return dummy objects to your controller.

One thing thats important to note is that its usually the case that mock objects implement the same interface as the objects that they are mocking - this allows your code to deal with them via the interface type, as if they are instances of the real thing.


Mocking and Mock Objects is not specific to Java. Mock objects is a unit testing technique in which a code chunk is replaced by dummy implementations that emulate real code. This helps one to write unit tests targeting the functionality provided by the class under test.

Check these articles which provide a very good introduction to the concept of mocking:
Mock Objects (PDF)
Endo-Testing: Unit Testing with Mock Objects (PDF)

If you are looking for a mock framework for unit testing in Java, have a look at: Mockito. I have found it useful for my unit tests.