The Mock Object

Intent: When a unit being tested has a dependency, replace that dependency with a version that is only for testing, called a mock object. The mock object can be conditioned and inspected by the test.

Example: An application makes use of a web service through an access object to obtain some critical information as part of its implementation. When testing the application, actually accessing the web service will make the test too slow and/or will produce results that the test cannot predict. Also, it is not certain the web service will always be available when the test is running.

The web service access object is replaced with a mock that is predictable, fast, and guaranteed. The test can determine what the mock will return and inspect if (and how) the application accessed it.

images

Figure 12: Mock object example diagram.

 

Note: This is only one way to create mock; in this case, using direct inheritance (which may not always be desirable). There are many other ways, any of which could be preferable depending on circumstances.

Qualities and Principles: The mock replaces a dependency, controlling coupling for the purpose of testing. The test's concern (application logic) is separated from the concern of the dependency, allowing the test to narrowly focus on the behavior it specifies. The interface of the mock is based on client need, as the test takes the same position as a client would/will. The mock is substitutable for the original dependency from the client point of view. The need/desire to make mocking possible in testing scenarios promotes the open-closed principle, as mocks must be introduced without changes to application logic.

Testing: The mock enables the test of the application under test. Mocks are inherently controllable by their own tests as well.

Questions and Concerns: There are many ways of creating mocks, including the use of a mock object framework to automate their production. Mocks should be kept as simple as possible to avoid excessive testing scenarios involving them. Mocks should not be public objects; they should be available only to test code and should be part of a test project or namespace.

Additionally, it must be decided how to replace the real dependency with the mock version while the test is running. This can be accomplished in various ways, including the use of a dependency injection framework.

For more information: https://tinyurl.com/yy7rv8lz

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.107.254