C# interfaces are a fundamental pillar of application architecture. They are one of the widely used method parameters when the desired outcome is decoupled system design independent from implementation details.
When unit testing such a method, a dummy implementation of an interface, also known as a fake or mock, is usually created with the goal to control a specific behavior or hold predefined data. By adding more unit tests, the fake implementations increase and their maintenance becomes time-consuming and a burden on productivity.
JustMock allows you to easily create a mock object without maintaining its physical implementation, which reduces the creation and maintenance costs significantly.
Here’s a simple example demonstrating how to mock an interface:
No physical file, no additional clutter. Еasy maintenance and increased productivity with just a few lines of code.
Controllable Behavior of the Mock Objects
When creating mock objects, JustMock allows you to control the behavior of each mock. You can program the mock to behave like an original instance and verify that methods are called in the right order, or all of its members to recursively generate new mock objects.
Creating a mock with RecursiveLoose behavior will also recursively create mock objects for all he mocked type members. This behavior ensures that a null value won't be returned for any chain call starting from the mock. This is the default behavior.
var foo = Mock.Create<IFirst>(Behavior.RecursiveLoose);
// This call will never encounter a NullReferenceException
var actual = foo.Second.Third.Fourth.DoSomething();
A mock created with CallOriginal behavior will have the original implementation for each of the non-explicitly arranged members. This is very useful when you want to preserve the original behavior of the code and just mock few properties or other members. Another use case is when you simply want to verify the number of times a member has been called.
A mock created with Strict behavior will throw a StrictMockException for all non-arranged members. This is very useful when you want to make sure that only arranged methods are called for a particular mock object during a test execution.
var foo = Mock.Create<IFoo>(Behavior.Strict);
A mock created with Loose behavior will create stubs for all void methods, will return a default value for all members returning value types and will return null for all members returning reference types. To access any chained calls, you will need to arrange explicitly the required members.