A great definition of Mocking from Wikipedia;
In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.
Moq provides us with an easy way of creating mock objects;
1 2 |
Mock<IContainer> mockContainer = new Mock<IContainer>(); Mock<ICustomerView> mockView = new Mock<ICustomerView>(); |
To access the actual instance of the object, we can access the Object property, which is strongly typed;
1 2 |
Mock<ICustomerView> mockView = new Mock<ICustomerView>(); ICustomerView view = mockView.Object; |
Moq provides you methods to confirm that particular actions took place on your mock object. For example, you may want to confirm that a method was called, a property getter or setter was called, or that a particular method was called a particular number of times.
To verify that a method was called, use the Verify method on the mock object;
1 |
mockCustomerRepository.Verify(t => t.Add(It.IsAny<Customer>())); |
The above code tests that the Add method was called on the mock repository object, and that it was called with "Any customer". You could tighten this up and say that you want a particularCustomer object to be passed in by using the It.Is method;
1 |
mockCustomerRepository.Verify(t => t.Add(It.Is<Customer>(t => t.Name == "Jon"))); |