Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
giri Avatar asked Jan 24 '10 18:01

giri


People also ask

What is mock object example?

For example, a mock object might assert the order in which its methods are called, or assert consistency of data across method calls. In the book The Art of Unit Testing mocks are described as a fake object that helps decide whether a test failed or passed by verifying whether an interaction with an object occurred.

What means mock object?

In object-oriented programming, a mock object is a simulated object that mimics the behavior of the smallest testable parts of an application in controlled ways.

How do you make a mock object?

Mock will be created by Mockito. Here we've added two mock method calls, add() and subtract(), to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using create(), the order of execution of the method does not matter.


1 Answers

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.

like image 143
danben Avatar answered Oct 14 '22 17:10

danben