Understanding Mock and frameworks - Part 2 of N

7 minute read

Continuing on where we left in the previous post - Understanding Mock and frameworks Part 1 – this post will take a very simple example and illustrate how to implement Mock frameworks.  I was mailed by one of our readers asking if I could define TDD – Test Driven Development in my words.

Test driven development is a methodology that states that test cases should be driving the design decisions and development.  This also that TDD advocates knowing the expected behaviour of our application (or a part of it), before we write the code.  It also enforces incremental design and allows us to write just enough code to pass our test. That means, no redundant code (YAGNI – You ain’t gonna need it) ships with our product, and our code is fairly simple (KISS – Keep it simple, stupid!) to understand. Sounds cool, isn’t it?

So you start writing tests first, design your application gradually and then start writing the implementation so that each test passes.  I prefer TDD over Test-After-Development (TAD) where you first design your application and write code.  Once your code is complete (or partially complete), you write the required test cases. Theoretically, a TAD system would appear to produce as high-quality product as TDD would.  But to my opinion, TAD involves taking design decisions up front – right from the start rather than taking incremental baby steps.  This also means that when time to delivery is short and critical, there are chances of not having a 100% code coverage by TAD approach. Also, a developer can fall victim to his own ego that “I don’t bad write code that needs to be tested”

That’s the way I see Test Driven Development (TDD) and Test-After-Development (TAD). So let’s get back to our topic of interest – an example to get started with Unit Testing with Mocks.

The service (or data source) interface

Assume that you are building an application that interfaces with just one service.  We have refactored our application to follow SOLID principles such as SRP, ISP, DIP and DI.  The service implements an interface IService.   This service interface could be interface of your internal service, or an external service whose behaviour and availability can not be controlled by you.

At this moment, we are not really interested in the implementation of IService and we will restrict our scope to the interface and the consumer (i.e. our application).

public interface IService
        string ServiceName { get; set; }

        bool Add(ServiceObject input);
        bool Remove(ServiceObject input);
        void Clear();
        int GetCount();
        ServiceObject GetObject(string name);

        void DataChanged(object sender, ChangedEventArgs args);

    public class ServiceObject
        public string Name { get; set; }
        public Guid Ref { get; set; }
        public DateTime Created { get; set; }

        public ServiceObject(string name, Guid reference)
            Name = name;
            Ref = reference;
            Created = DateTime.Now;

    public enum Action

The Controller (or our application)


The consuming class (let’s call it Controller) isolates the dependency on the implementation of service object and ensures that the consuming class injects the appropriate service object.

public class Controller
        private IService _service;       

        public Controller(IService service)
            _service = service;

In reality, the Controller class could be just a facade or can contain business logic, or data manipulation and a lot of other complex logic.  For this example, it is kept simple and restricted to only service calls.   So our controller class looks like,

  1. public class Controller
  2. {
  3.     private IService _service;
  5.     /// <summary>
  6.     /// To demonstrate events in Mock
  7.     /// </summary>
  8.     public event EventHandler<ChangedEventArgs> CEvent;
  10.     public Controller(IService service)
  11.     {
  12.         _service = service;
  13.     }    
  15.     private void RaiseEvent(Action action,
  16.                     ServiceObject input)
  17.     {
  18.         /* Can have more business logic here */
  19.         if (CEvent != null)
  20.             CEvent(this, new ChangedEventArgs(action, input));
  21.     }
  23.     /// <summary>
  24.     /// To demonstrate methods with parameters and return value
  25.     /// in Mock
  26.     /// </summary>
  27.     public bool Add(ServiceObject input)
  28.     {
  29.         if (input == null)
  30.             return false;
  32.         /* Can have more business logic here */
  34.         _service.Add(input);
  35.         RaiseEvent(Action.Add, input);
  37.         return true;
  38.     }
  40.     /// <summary>
  41.     /// To demonstrate simple method calls in Mock
  42.     /// </summary>
  43.     public void Clear()
  44.     {
  45.         _service.Clear();
  46.     }
  47. }


So to create an object of our controller, we need to pass an instance of a class that implements IService. As said earlier, we will not implement the interface IService to ensure that we do not have a functional service (to create a scenario of an unavailable service) for testing.  So let’s get started with our Mocking the interface IService.


Mocking – Step Arrange

All our tests will follow three step process

  • Arrange – This step involves creating a service/interface mock (using a Mock framework) and creating all required objects for that service/interface.  This step also includes faking the object behaviour.
  • Act – This step involves calling a method of the service, or performing any business functionality
  • Assert – This step usually asserts whether the expected result is obtained from the previous step (‘Act’) or not

Step Arrange: With Rhino Mocks

Rhino Mock framework maintains a repository of Mocks.   The MockRepository can be seen to follow a Factory design pattern to generate Mocks using Generics, object(s ) of Type, or stubs.  One of the ways to generate a Mock is,

  1. // Arrange
  2. var service = MockRepository.GenerateMock<IService>();
  3. var serviceStub = MockRepository.GenerateStub<IService>();

There is a minor difference between a Mock and a Stub. A discussion on StackOverflow explains it very appropriately or Martin Fowler has explained it brilliantly in his post on Mocks Aren't Stubs. To keep it short and simple,

Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations. Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behaviour, state of the “fake”object in order to utilize a test scenario.

If you want to verify the behaviour of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn't the focus of this test, you will use a stub.

Once the object has been created, we need to mock the service behaviour on this fake service object.  Let’s see how to fake a property

  1. // Arrange
  2. var service = MockRepository.GenerateMock<IService>();            
  3. service.Stub(x => x.ServiceName).Return("DataService");

Similarly, we can mock methods.  We will see mocking different types in detail later.


Step Arrange: With NSubstitute

NSubstitute makes it simpler to read, interpret and implement.

  1. // Arrange
  2. var service = Substitute.For<IService>();

Mocking property in NSubstitute is a lot easier to remember

  1. // Arrange
  2. var service = Substitute.For<IService>();            
  3. service.ServiceName.Returns("DataService");

Step Arrange: With Moq

Moq like Rhino Mocks also has MockRepository.  You can choose a mock to be a part of MockRepository or to let it hang individually.  Both the methods are shown as below.

  1.           // Arrange
  2.             var service = newMock<IService>();
  4.           MockRepository repository = new MockRepository(MockBehavior.Default);
  5.           var serviceInRepository = repository.Create<IService>();

Mocking property is somewhat similar to Rhino Mocks

  1.           // Arrange
  2.             var service = newMock<IService>();
  3.           service.Setup(x => x.ServiceName).Returns("DataService");

Rhino Mocks and Moq both have two different types of behaviours' – Strict and Loose (default).  We will look into what each of them means in the next article.

Mocking – Step Act, Assert

Once we have the fake service and have defined the expected behaviour, we can implement the next step.  This step involves calling a method of the service, or performing any business functionality. So here we can call a method of service, or use its output to do some work.  So our examples will vary from setting something in mocked service object to calling its methods.

Step Act and Assert: With Rhino Mocks and NSubstitute

As the output of the first step, both Rhino Mock and NSubstitute give you directly an object of IService (named, service).  So you can directly use this object as a substitute of the actual service.  The object service is a fake object whose ServiceName is expected to be "DataService".  Just to remind that in actual, neither the implementation of the service nor a real object of the service exists.  We are dealing with fake objects through all our examples

  1. // Act
  2. var actual = service.ServiceName;
  4. // Assert
  5. Assert.AreEqual("DataService", actual);

This test on execution will give a PASS

Step Act and Assert: With Moq

Moq unlike the other two frameworks does not directly provide you a fake service object.  It provides you the fake service object in one of its properties called ‘Object’.  Everything else remains the same

  1. // Act
  2. var actual = service.Object.ServiceName;
  4. // Assert
  5. Assert.AreEqual("DataService", actual);

If you put together the code, it forms our first Unit Test w/Mock frameworks.

The Code for Download

Understanding RhinoMocks, NSubstitute, Moq by Puneet Ghanshani

In the next article, we will look into creating Mocks for methods using these frameworks.