Moq: Mock a method from an interface
If you have a class using a method from one or more interfaces, you can use Moq to fake the behavior of the methods from the interface. Your code can still work with the class directly.
What is Moq
Moq is a powerful mocking library for C#.
Moq is designed to be a very practical, unobtrusive and straight-forward way to quickly setup dependencies for your tests.
It is very useful for faking implementations of interfaces so that you don't need to litter your tests with implementations that you don't need.
The code below shows a class,
MyClass, which calls a method on a complex object internally. We do not want to test the
ComplexClass class here, only the behavior of the
How to test the behavior of MyClass's
Verify method? Use Moq to setup the implementation.
Verify_ComplexObjectIsValid_ShouldNotThrowException test method fails because the
complexClassobject has not been set up with the needed dependencies.
Verify_ComplexObjectIsValid_ShouldReallyNotThrowException test method, Moq fakes the behavior of the
ComplexClass.Verify method and sets up an expectation that this method should be called. Now we just verify that no exception is being thrown and that this method is called.
The behavior of MyClass was successfully tested without need of coupling the test with ComplexClass's internal logic.