Understanding Mock and frameworks – Part 2 of N
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 { Add, Remove, Clear }
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,
- publicclassController
- {
- privateIService _service;
- ///<summary>
- /// To demonstrate events in Mock
- ///</summary>
- publiceventEventHandler<ChangedEventArgs> CEvent;
- public Controller(IService service)
- {
- _service = service;
- }
- privatevoid RaiseEvent(Action action,
- ServiceObject input)
- {
- /* Can have more business logic here */
- if (CEvent != null)
- CEvent(this, newChangedEventArgs(action, input));
- }
- ///<summary>
- /// To demonstrate methods with parameters and return value
- /// in Mock
- ///</summary>
- publicbool Add(ServiceObject input)
- {
- if (input == null)
- returnfalse;
- /* Can have more business logic here */
- bool output = _service.Add(input);
- RaiseEvent(Action.Add, input);
- return output;
- }
- ///<summary>
- /// To demonstrate simple method calls in Mock
- ///</summary>
- publicvoid Clear()
- {
- _service.Clear();
- }
- }
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,
- // Arrange
- var service = MockRepository.GenerateMock<IService>();
- 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
- // Arrange
- var service = MockRepository.GenerateMock<IService>();
- 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.
- // Arrange
- var service = Substitute.For<IService>();
Mocking property in NSubstitute is a lot easier to remember
- // Arrange
- var service = Substitute.For<IService>();
- 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.
- // Arrange
- var service = newMock<IService>();
- MockRepository repository = newMockRepository(MockBehavior.Default);
- var serviceInRepository = repository.Create<IService>();
Mocking property is somewhat similar to Rhino Mocks
- // Arrange
- var service = newMock<IService>();
- 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
- // Act
- var actual = service.ServiceName;
- // Assert
- 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
- // Act
- var actual = service.Object.ServiceName;
- // Assert
- 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 Punit Ganshani
In the next article, we will look into creating Mocks for methods using these frameworks.
Punit Ganshani
Punit Ganshani, based out of Singapore, specializes in Microsoft technology stack and performance engineering. He is an open-source contributor at Codeplex, has several apps on Windows Phone Store and is a noted speaker on Performance Tuning, Mobile Development and Application Design
Related posts:
- Understanding Mock and frameworks – Part 1 of N We have several posts on the Internet that focus on...
3 Responses to Understanding Mock and frameworks – Part 2 of N
Start Contributing!
If you have the knack of writing to share your knowledge with other spirited minds, you can register yourself and get started...
For more information, please visit our Contribute page
Register / Sign In
Information classified
- Announcements (1)
- Code (17)
- .NET (13)
- CSS and HTML (1)
- Database (1)
- Java (1)
- Javascript (1)
- Open Source (6)
- Web Services (1)
- Design (1)
- How-to (18)
- Office 365 (1)
- Server (4)
- SharePoint (8)
- TDD (4)
- Windows 8 (3)
- Presentations (1)
- Promotions (6)
- Uncategorized (1)
Latest on the Stack
- Complete guide to dynamic keyword in C#
- Sharing code: Adding NavigationService
- Mock driven development using .NET
- XecMe – Windows Service Host
- How to Write Access 2013 Custom Web App on Office 365
- Portable Class Library – Articles and Sample References
- Extension SDKs in Build Server without installing it!
- SharePoint 2013 and Search with REST API and ODATA
- Search Engine Changes in SharePoint 2013
- Consuming Odata Service in Windows Store Apps (Include MVVM Pattern)
Twitter Updates
- XecMe - Windows Service Host is.gd/0fjCQb #windowsservices #xecme 6 hours ago
- Sharing code: Adding #NavigationService is.gd/0DDj9G #SharingCode #WindowsPhoneapp #WindowsStoreApps 10 hours ago
- Complete guide to dynamic keyword in C# is.gd/Emmaju #net #development 10 hours ago
- Mock driven development using .NET is.gd/GeHGLe 14 hours ago
- XecMe - Windows Service Host is.gd/0fjCQb #windowsservices #xecme 18 hours ago
Coming Soon














[...] Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq [...]
[...] Understanding Mock and frameworks – Part 2 of N JavaScript – Lazy Loading Using RequireJS [...]
[...] Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq [...]