When to MockObject?
In my previous post I showed how to mock future instances. Now we will see when to use MockObject.
What is the difference?
The difference is quite simple. But before we delve into it we should talk about the 2 objects that are associated with each mock.
Each mock has a controller that controls the behavior. This is done using the Mock type. Here we setup the Expectations and Validations. And each mock has the actual instance that is being mocked.
Using MockManager.Mock will mock a future instance.
Using MockManager.MockObject will immediately create a mocked instance. It is possible to access this instance using the mock.Object property. (Other mocking frameworks have only this option)
After creating a MockObject we can then pass this object as an argument to our tested method to inject the Mock.
[Test] public void MockObjectTest() { MockObject controlListener = MockManager.MockObject(typeof(MyListener)); MyListener mockedListener = (MyListener)controlListener.Object; // Setup expectation // inject our mocked object into our test Messages.Broadcast("I am alive",mockedListener); // Assertions… }
Note: There is no need for MyListener to be an interface, it could even be a sealed class!
What about interfaces?
When the mocked type (MyListener) is an interface or an abstract class TypeMock will create a new Type on-the-fly, that extends the mocked interface. This new object can then be passed to our tested code.
Mocks returning Mocks
A mocked expectation can return another mock. Here is an example
public class MyFactory { public MyListener GetListener() { // Get Listener through some complex external services } }
We can now setup the expectations that GetListener() will return a mocked MyListener.
[Test] public void MockObjectTest() { // mock future instance of MyFactory Mock factory = MockManager.Mock(typeof(MyFactory)); // create a MockObject of MyListener MockObject controlListener = MockManager.MockObject(typeof(MyListener)); MyListener mockedListener = (MyListener)controlListener.Object; // Setup expectation factory.ExpectAndReturn("GetListener",mockedListener); }
Summary
Here is a list of places where you should use MockObject.
- When a mocked object is passed to the tested method.
- When you need to mock an abstract class and interface.
- When a mocked method returns a mocked type










Leave a Reply