What is a Mock Object?

In object-oriented programming, mock objects are fake objects that simulate the behavior of real objects in a controlled manner. Programmers usually create mock objects to test the behavior of other objects, much like car designers use crash test dummies to simulate the dynamic behavior of people in vehicle collisions.

The mock object uses the mock version of the object to replace dependent classes. After these mock objects are passed to the class to be tested, the dependency relationship is replaced by the mock version of the object, and the test object still thinks of itself You are dealing with real objects.
Before the mock object framework, mock objects were written by hand.
The premise of using mock objects is that the interface of the cable-dependent unit must be clearly defined. [1]
in
The simulated object has the same properties as the real object to be simulated
use
The use of mock objects may tightly couple unit tests with the implementation of the code under test. For example, many mock object frameworks allow developers to specify the order and number of calls to methods on mock objects. In this way, refactoring the code after the test passes, even if the method still adheres to the previously implemented contract, may cause the test to fail. This means that unit tests should test the external behavior of the method, not its internal implementation. Excessive use of mock objects in unit test test cases may cause continuous refactoring as the system develops, which will cause a significant increase in the workload of maintenance testing itself. In the course of development, incorrect maintenance of such tests may miss false positives and be caught in tests using real objects. Conversely, simply simulating a method may require less configuration than setting up the entire real object, thus reducing the maintenance required.
Simulated objects must accurately model the behavior of the objects they are simulating. However, if the object to be simulated comes from another developer or project, or if it has not been developed yet, accurate modeling is difficult to achieve. If the behavior is not modeled correctly, the unit test record may pass, and when it is actually run, the test may fail under the same conditions. [1]

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?