Total votes: 1
Category: Design Patterns
Print: Print Article
Please login to rate or to leave a comment.
Published: 20 Apr 2009
Download Sample Code
This article gives a quick introduction in the usage of two of the most known mocking frameworks: Rhino Mocks and Moq.
When using TDD  to develop an application it is essential that the system under test (SUT) can be tested in isolation. That is, only the
class that I am currently developing is “real” and all other parts are simulated or faked. If my SUT needs to collaborate with other components
those other components are mocked during the test. We can either manually implement such mock objects or use a mocking framework for this task.
There exist several well known mocking frameworks for the .NET platform. In this article I’ll give a short introduction in the two most used
OSS mocking frameworks. The first is Rhino Mocks  which was developed by Oren Eini, aka Ayende  and the other one is Moq  developed by
Daniel Cazzulino .
Preparing the System
To start using one of the mocking frameworks you have to first download it. You can do this here  if you want to use Rhino Mocks
or here  if instead you want to work with Moq. Both frameworks are part of the code accompanying this article. You find the libraries
needed in the lib sub-directory of the download.
Create a new folder on your system. Call it MockingSample. Create a sub-
folder called lib and copy the files nunit.framework.dll, rhino.mocks.dll and moq.dll into this directory. As
mentioned above you find these three libraries in the lib folder of the code to download.
The easiest way to generate a mock object is to provide an interface to the mocking framework. The framework then creates an
implementation of this interface which is automatically instrumented such as that behavior of the system under test can be verified
through the mock object.
A mocking framework like Rhino Mocks can also mock an existing implementation. But there is one caveat;
the methods called must be virtual. The reason is that the mocking framework automatically “wraps” the component to be mocked into a
proxy object. To accomplish this he proxy object inherits from the component and overrides the members. But only virtual members can be
If you cannot mock an object since it implements no interface and its methods are not virtual you can still build a thin
wrapper around the object to mock and then mock the wrapper during the test. This is also called the adapter pattern .
Why should I use mock objects?
Imagine you want to develop an order service which needs some data from the database. The SUT in this case is the order service. We want to
test this order service in isolation. Why? It is not always possible or it is too much work involved to provide e.g. a real database with
realistic data to the developer during testing. Doesn’t it make sense in such a situation to replace the real database access with a faked one?
Another scenario is the following: you have to implement an email publisher which sends emails to subscribed people when some event in the
system happens. During the test you do not want to send real emails to people. You don’t want to be identified as a spammer, don’t you? In such
a situation we mock the email sender.
But let me say the following: not every object must be mocked. It makes absolutely no sense to mock
an object that is a pure data container and has no behavior or any external dependencies. Typical examples of this kind of objects are the so
called data transfer objects (DTO). Such objects can be used as they are and must not be faked.
A simple use case
We have to develop an order service. The order service creates new orders with the aid of an order factory and retrieves pre-existing orders
from the database through an order repository. Whenever a customer that has unpaid orders places a new order an email is sent to the manager
for approval of the new order.
In this simple sample we can already identify three components which collaborate with the order service.
These are the order factory, the order repository and the email sender. Those three components we will want to mock when implementing and unit
-testing the order service.
You will realize however that this list is not complete. There will certainly be other components to mock
whilst developing the order service.
In the picture below you can see the class diagram of our simplified domain model. There is an order service class which has three external
dependencies. All dependencies are tied to interfaces and NOT to implementations. This makes unit testing very easy since all three
dependencies can be easily mocked during the test.
Figure 1: The domain model
The first operation we want to implement is the PlaceNewOrder method of the order service. We want to do this test driven. Thus I
prepare my solution accordingly and create the following solution structure.
Figure 2: Structure of the solution
The project named Core contains the logic to implement and the project called UnitTests contains all unit tests or, as
I prefer to call them, the project contains the specifications. To streamline my specifications I use to work with a SpecificationBase
class. This class is very simple but it allows me to implement my specifications in a BDD  like manner, that is I use the schema
The Given method contains all code needed to setup or prepare the test or as one also says: to prepare/define the
context. The When method will contain the operation (-call) we want to test. The Then’s are the individual test methods which will be
decorated with the Then attribute.
To support the usage of the Given->When->Then syntax I also need to implement a
special attribute which derives from the TestAttribute of NUnit. I call this the ThenAttribute.
Now finally let’s see some real code. I create a specification for the task I want to accomplish. The name of the specification
class should reflect my intent. In this case my intent is to place a new order. Thus my definition is as follows
Note how the name of the class is rather long (this is desired) and starts with the prefix when.
Introducing Rhino Mocks
Now to be able to place a new order the order service needs an order factory. This order factory will be mocked. The mocked order factory
will then be injected into the order service via the constructor. All this is setup code and will thus be placed into the Given method
of my specification. A new order is placed by a specific customer so I’ll also need an id for this customer.
Note the first line in the Given method. That’s how Rhino Mocks can be used to create a mock based on a given
interface. Just call the static and generic method GenerateMock of the MockRepository class. Here Rhino Mocks will
automatically generate an implementation for the interface IOrderFactory and return this implementation and assigns it to the field
orderFactory. In the second line the mocked factory is injected into the service. It is very important to note that the order service
will NOT realize that the injected factory is not the “real” factory but just a mocked one. The order service only realizes that it receives an
object which implements the expected interface IOrderFactor.
Now let’s specify the actual operation we want to implement. This is
done in the When method of the specification. In our case
Obviously I call a method PlaceNewOrder (which has to be implemented afterwards) and pass it the previously defined
Now I want to use my mock object (together with the mock framework) to verify expected behavior of the order service. In
this case I want to verify that the method PlaceNewOrder calls the method Create of the order factory and passes the right
parameter (the id of the customer). This verification I will implement in a method that I decorate with the Then attribute. The code
needed to verify my expectation is
This is a very short assertion but it looks quite strange if you are not used to lambda expressions . But it’s quite easy to
explain what happens. The Rhino Mocks framework defines an extension method  AssertWasCalled which can be applied to any object.
Here it is used on the mocked order factory. The lambda expression
factory => factory.Create(customerId) which is passed as a
parameter tells the mocking framework which operation we want to assert. In this case it’s a call of the method Create on the mock
object. Not only do I expect a call to the method but also the parameter(s) of the call have to be as expected.
If I want to have more
control over the expectations regarding parameters of a call Rhino Mocks offers different possibilities. The following line of code just
expects a call to the Create method but the parameter is ignored
The above code uses the second overload of the AssertWasCalled method which expects a lambda expresssion which defines
constraints or expectations on the parameters. In this case we have declared by the expression
c => c.IgnoreArguments() that
we want to ignore any argument of the call. Note that we still have to pass some value as parameter and in this case I have chosen to pass the
Now I also want to show how we can instrument the mock object such as that it e.g. returns a specific value
when a certain method is called. In our case I’ll illustrate that with the order factory mock object. The mock object shall return a prepared
order object when we call its method Create. This instrumentation is part of the setup code and thus belongs into the Given method of our
specification. With the following code
I first line I define a new (dummy) order object and then specify in the second line that the mock object should return this
dummy object when called. Note the Stub method which is also an extension method defined by the mocking framework. Note also the
Return method which allows me to instrument the mock such that it returns precanned data.
The Moq framework is very similar to Rhino Mocks. To create a new mock object we do not use a static method but rather
instantiate a generic mock object
The type of this object is
Mock<IOrderFactory> which is different compared to Rhino Mocks. We have access to
the mocked object via the property Object of the mock. Thus instantiating the factory service and injecting the mocked factory the syntax is as
To verify behavior Moq uses the method Verify of the mock object. This method also expects a lambda expression
similar to the one used with Rhino Mocks. If we want to verify the call and the parameters the code is like this
If we only want to verify the call regardless of the parameter passed we can do this like so
The full code of the unit test using Moq is shown below
Evidently it is very similar to the one needed when using Rhino Mocks.
In this first part of a series of articles about mocking frameworks I have introduced the concept of mocking and the reasons to do so. I
have defined a simple yet realistic use case and have demonstrated within this use case how Rhino Mocks or Moq can be used to mock external
dependencies of the component or class I want to test.
In the next part of this series I’ll show some advanced usage scenarios and how
the two mocking frameworks can be used in these situations. Stay tuned.
In this article I have given a quick introduction in two of the most known mocking frameworks for the .NET platform. I have shown how either
of these two frameworks can be used to create and configure mock objects. I have also shown how behavior of the system under test (SUT)
accessing these mock objects can be verified. Both frameworks allow the developer to develop a new class in complete isolation when simulating
all other components by mock objects.
Gabriel Schenker is a independent consultant, trainer, mentor and developer. He lives in Switzerland near to Zurich. His special focus is on practicing lean or friction-less software development. This includes practicing TDD, BDD and DDD. He is constantly advocating, promoting and supporting a cont...
This author has published 4 articles on DotNetSlackers. View other articles or the complete profile here.
Other articles in this category
Introduction to StructureMap
Have you heard of StructureMap, generally know what it’s for, and want to know how to get started qu...
DI Patterns: Constructor Injection
In this article, an excerpt from the book "Dependency Injection in .NET", we will take a detailed lo...
The Command Pattern
In this article I will provide a quick refresher on what the command pattern is used for, how it wor...
Brian Mains discusses how to implement the Arrange-Act-Assert pattern in TypeMock.
Key Process Patterns
This article, based on chapter 2 of Specification by Example, presents effective patterns for softwa...
You might also be interested in the following related blog posts
Introducing SharePoint 2010 Training at U2U
The Underground at PDC
10 resources to learn Moq
My History of Visual Studio (Part 6)
Why not Classic (Legacy) ASP?
BeginDialOut with Office Communicator Clients
SOA Patterns presentation on E-VAN (recording)
DotNetNuke Fusion Results for Q3
Successive Method Calls With MoQ
GiveCamps Get a new Sponsor
Please login to rate or to leave a comment.