Creation of Mocks – On the difference between Mock and MockObject
One of the most confusing points when dealing with Typemock Isolator is the creation of Mock Controllers (the term Mock controller refers to the object which is used to define the behavior of the mocked object during the test). When creating these controller there are two sets of API one can use:
The difference between the two is quite simple: to
Using the Mock API tells the framework to attach the created Mock Controller to the next instance that will be created (in the future). This means that the next time a new call will be issued for the given type, a Mock Controller will be attached to the created instance which will cause all calls on that instance to be mocked.
Using the MockObject API tells the framework to create a Mock Controller and an instance of that type and attach them to one another. The real instance that is mocked is created immediately and it can be accessed through the MockObject.Object property.
So when to use which?
The Mock API is used when the creating of the instance we wish to mock is done internally in the tested class and we have no convenient way of accessing it.
The MockObject API is used when the instance we want to mock is created outside the tested class and is passed to it. The nice thing about the MockObject API is that unlike the Mock API it can handle types that usually cant be instantiated such as interfaces & Abstract classes
Another related issue which usually goes hand in hand with the usage of these API’s is the handling of Unexpected Calls (we refer to calls which have no expectations set on them as Unexpected Calls).
When using the Mock API we always mock concrete classes, for which all methods have real implementation. By default when mocking these types all Unexpected Calls will be directed to the real code. In most cases this is the intent of the user.
When using the MockObject API, more often we mock Interfaces/Abstract classes. And since for these not all methods have real implementation, by default issuing an Unexpected Calls will result in an exception being thrown. From our experience Unexpected Calls in these cases indicates a logic flaw in most cases.
(There are some cases in which the MockObject API is used to mock concrete classes, in these scenarios the behavior is the same as if using the Mock API since the actual default is determined by the type of the class being mocked and not by the API itself)