Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Object Mocking and when do I need it?

Many people use Mock Objects when they are writing unit tests. What is a Mock Object? Why would I ever need one? Do I need a Mock Object Framework?

like image 739
Mike Minutillo Avatar asked Aug 07 '08 02:08

Mike Minutillo


People also ask

Why do we need to mock objects?

Using mock objects allows developers to focus their tests on the behavior of the system under test without worrying about its dependencies. For example, testing a complex algorithm based on multiple objects being in particular states can be clearly expressed using mock objects in place of real objects.

What happens when we mock an object?

To isolate the behavior of the object you want to test you replace the other objects by mocks that simulate the behavior of the real objects. So in simple words, mocking is creating objects that simulate the behavior of real objects. In unit testing we want to test methods of one class in isolation.

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.


2 Answers

Object Mocking is used to keep dependencies out of your unit test. Sometimes you'll have a test like "SelectPerson" which will select a person from the database and return a Person object.

To do this, you would normally need a dependency on the database, however with object mocking you can simulate the interaction with the database with a mock framework, so it might return a dataset which looks like one returned from the database and you can then test your code to ensure that it handles translating a dataset to a person object, rather than using it to test that a connection to the database exists.

like image 65
lomaxx Avatar answered Oct 17 '22 09:10

lomaxx


Several people have already answered the 'what', but here are a couple of quick 'whys' that I can think of:

  1. Performance

    Because unit tests should be fast, testing a component that interacts with a network, a database, or other time-intensive resource does not need to pay the penalty if it's done using mock objects. The savings add up quickly.

  2. Collaboration

    If you are writing a nicely encapsulated piece of code that needs to interact with someone else's code (that hasn't been written yet, or is in being developed in parallel - a common scenario), you can exercise your code with mock objects once an interface has been agreed upon. Otherwise your code may not begin to be tested until the other component is finished.

like image 20
Joshua McKinnon Avatar answered Oct 17 '22 08:10

Joshua McKinnon