Search code examples
unit-testingtddmockingmoqtestdrivendesign

The Purpose of Mocking


What is the purpose of mocking?

I have been following some ASP.NET MVC tutorials that use NUnit for testing and Moq for mocking. I am a little unclear about the mocking part of it though.


Solution

  • The purpose of mocking is to isolate the class being tested from other classes.

    This is helpful when a class :

    • connects to an external resource (FileSystem, DB, network ... )
    • is expensive to setup, or not yet available (hardware being developed)
    • slows down the execution of the unit tests
    • has a non-deterministic behavior
    • has (or is) a user interface

    It also makes it easier to test for error conditions, as your build your mock object so that it returns and error, throw an exception ...

    The mock can record how it was invoked (function calls order, parameters) and this can be verified by the test. EDIT: For instance: The method you're testing sends a message, such as an IPC. The method of the mock object can record how many times it was invoked, the parameter he received (i.e. the message to be sent). Then the test can interrogate the mock object and assert on the number of messages sent, the content of the message ... Likewise, the mock object can record the methods that are called in a log string and the test can retrieve that string and assert on it.

    Do not abuse of mock objects: test the behaviour rather than the implementation, or the unit tests will be too tightly coupled to the code, and brittle (break at refactoring).

    Mock can be coded manually, or generated by a mocking framework.