Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep Mock object in sync with target object

I am asking about mock object management, regardless the specific implementation (EasyMock, Mock Object etc).

I have been reluctant to use Mock object in my unit testings, for the following reason: The behavior of Mock object must mirror the behavior of object being mocked. If the behavior of the object being mocked has changed, we will have to change behavior of mock object as well. If we don't, the behavior of mock object will out of sync with the real object, and thus make the unit-testing meaningless, and it's dangerous.

My question are, how to keep the mock object in sync with target object? How do you propagate the changes? Do you use any mock object management technique?

Edit: Change title to narrow down the scope.

like image 593
janetsmith Avatar asked Mar 07 '11 01:03

janetsmith


People also ask

What is the difference between mocking and stubbing?

Stubbing, like mocking, means creating a stand-in, but a stub only mocks the behavior, but not the entire object. This is used when your implementation only interacts with a certain behavior of the object.

What happens when you mock an object?

What happens when you mock something? First of all, we should define what a mock is: In a unit test, mock objects can simulate the behavior of complex, real objects and are therefore useful when it is impractical or impossible to incorporate a real object into a unit test. Mocking makes sense in a unit testing context.

What is the goal of using mock object for mocking?

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's the difference between mock and spy objects?

Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it. When using mock objects, the default behavior of the method when not stub is do nothing.


1 Answers

Well defined APIs should not have this sort of leeway: given a set of input, the object being mocked should only behave in these particular ways: the behavior is tied to the interface. If there is allowed variance, then your mock object should be testing all of the different things this object could do.

You can mitigate the risk of behavior drift by:

  • Integration testing, and
  • Comparing your mocked data with the real implementation.
like image 128
Edward Z. Yang Avatar answered Oct 07 '22 01:10

Edward Z. Yang