Description:
In object oriented programming, mock objects are simulated objects that mimic the behavior of real objects. Mock objects are usually used in Unit Testing.
Mock objects are exactly created to test the behavior of some other (real) object. Therefore, mocking is all about faking the real object and doing some operations in a controlled way so that the returned (test) result is always valid.
The first question that is asked is “Why to use mock objects?”, and there are several reasons for this. imagine you have a real object with the following characteristics (the list is taken from Wikipedia):
There are two types of Mocks:
The need for mock objects:
A Mock Object:
Mock framework:
Commonly used Mock Frameworks:
--------------------------------------------------------------------------------------
Moq is intended to be simple to use, strong typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).
Authors of Moq called it The simples mocking library for .NET and Silverlight. I am not fully sure if it is the simplest but I may confirm that is really simple and powerful which is why I particularily like using Moq.
You may define mocks for the following:
If you want to install it manually, just download the library from the official website and reference it from your project.
The following will be our base code which will be tested:
as you may see, we have a
Let’s explain what is going on the basic test above:
creates a new object that implements all the methods and properties as
defined in the
on the other hand, Moq uses a very simple notation which is as follows
the above code does two things:
As you may see, the class implements the
Rhino Mocks objects allows Expectations, Constraints and Callbacks to be setup, specifying how the tested object should interact with the mocked object. These conditions are evaluated throughout the test run, and fails early in order to give you a warning as localizable as possible.
Rhino.Mocks features:
Here is how Rhino Mocks would handle the previous tests:
[Test]
public void RenterPaysForCar ()
{
MockControl mockCar= MockControl.CreateControl(typeof(ICar));
MockControl mockPerson = MockControl.CreateControl(typeof(IPerson));
ICar car = controlCar.GetMock() as ICar;
IPerson person = controlPerson.GetMock() as IPerson;
mockCar.ExpectAndReturn(car.CurrentPrice, 115);
mockCar.ExpectAndReturn(car.RentedFrom,DateTime.Now.AddDays(-7));
mockCar.ExpectAndReturn(car.RentedBy,person);
ICarRental avis= new AvisCarRental();
mockCar.SetupResult(car.ReturnToParkingLot(avis))
mockCar.Callback = new
CarRentalDelegate(InformReachedParkingLot); person.Pay(avis,850);
avis.ReturnCar(car);
controlCar.Verify();
controlPerson.Verify();
}
delegate void CarRentalDelegatE(ICarRental carRental);void InformReachedParkingLot(ICarRental carRental)
{//assumes that car is an instance variable, not a local variable in the test
carRental.CarInParkingLot(car);
}
In this case, it's not much of a difference, that is because we are using expectations), the same way EasyMock.Net works. Let's try something more difficult, let's assume that when the car rental sends the car to its parking lot, they require the car to inform that it arrived safely before letting the renter go. In essence, classic threading problem, but one that is very hard to solve using NMock. I created a couple of hacks in order to solve. Usually the solution for those kinds of problem is to write your own test class. This isn't very practical[5] for large number of classes, here is how I would solve this using Rhino Mocks, I'll leave you implementing the same with the other framework.
You can see that we set up a callback for ReturnToParkingLot, and using that callback we get the ICarRental reference that we got. So we can do call the CarInParkingLot() andreturn from ReturnCar() method.
Another way to specify conditions is to use constraints, they are used in much the same way as they are in NMock:
car.AddGas(0);
mockCar.Constraints(new IsEqualOrLessThan(150));
The Last Method concept:
Most actions in Rhino.Mocks are done on the last method call, after each call, you can setup more information about the call: Return value, if and what to throw, constraints and callbacks. You set these conditions by calling the methods on the MockControl (Returns, Throws, Constraints and Callback). Most methods has overloads that allows you to setup returning or throwing for multiply calls of the same method. Rhino.Mocks ensure that all the requirements of a method are satisfied before the next method can be recorded, this means that for methods that return values, a return value or an exception to throw need to be set. You can setup several behaviors for a single method. The same method but with different arguments mean a different method call, as far as Rhino.Mocks is interested.
Return Value:
A method that returns a value must define either Returns or Throws or their equivalents ( ReturnsFor(), ThrowsFor(), AlwaysReturns, AlwaysThrow, SetupResult() or ExpectAndReturn() ).
Tips & Tricks:
Callbacks:
A callback need to match the last method signature, but is free to have a different return type (or no return type, of course). The return value of the callback is ignored, so don't expect to return some value from the callback and get it from the mocked method. This is by design and is meant to reduce the chance that the callbacks will be abused.
Mocking Classes:
Rhino.Mocks can mock classes if they inherit from MarhsalByRef, it's not a recommended approach. Use of interfaces is highly recommended.
Gotcha:
Expect Call
To create any mock object you need to create instance of MockRepository Class which act as project presenter.
I am taking very simple example how to create mock object and set expectation on property.
--------------------------------------------
I’ve heard multiple people state that they prefer Moq over Rhino Mocks because the Rhino Mocks syntax isn’t as clean. And while I don’t have a strong preference between the two, I’d like to help dispel that myth. It is true that, if you choose the wrong syntax, Rhino can be more complicated. This is because Rhino has been around for a while and it’s original syntax pre-dates the improved Arrange/Act/Assert syntax. I go into a lot more detail on Rhino Mocks and the appropriate way to use it , but to dispel the myth that Rhino Mocks is complicated I would like to compare the syntax for creating stubs and mocks using Rhino vs. Moq:
Moq Syntax:
Moq syntax using MoqAutoMocker:
I have to say, I did prefer Moq slightly to Rhino Mocks. The newer Arrange, Act, Assert (AAA) style syntax in Rhino Mocks is a huge improvement over the old Record/Replay mess. But Moq has the benefit of being born at the right time and has AAA style calls without the burden of supporting deprecated syntax. This means Moq has cleaner documentation, fewer options, and fewer ways to get confused by the API. I really couldn’t find anything I needed to do in Moq that I couldn’t do. I did get a little tripped up having to get the object out of the mock, with myMock.Object calls, but that wasn’t a big deal.
Here’s the NuGet Moq install package syntax to add Moq to your unit test project:

In object oriented programming, mock objects are simulated objects that mimic the behavior of real objects. Mock objects are usually used in Unit Testing.
Mock objects are exactly created to test the behavior of some other (real) object. Therefore, mocking is all about faking the real object and doing some operations in a controlled way so that the returned (test) result is always valid.
The first question that is asked is “Why to use mock objects?”, and there are several reasons for this. imagine you have a real object with the following characteristics (the list is taken from Wikipedia):
- the object supplies non-deterministic results (e.g., the current time or the current temperature);
- has states that are not easy to create or reproduce (e.g., a network error);
- is slow (e.g., a complete database, which would have to be initialized before the test);
- does not yet exist or may change behavior;
- would have to include information and methods exclusively for testing purposes (and not for its actual task).
There are two types of Mocks:
- Strict or True Mocks in which case an exception is thrown for anything that doesn’t have a corresponding expectation
- Loose Mocks: which never throws and returns default values or empty arrays, enumerables
- act as proxy objects
- give the possibility to “Setup” the return (result) and control the validity of input parameters
The need for mock objects:
A Mock Object:
- is easily created
- is easily set up
- is quick
- is deterministic
- has easily caused behavior
- has no direct user interface
- is directly queriable
- real object has non-deterministic behavior
- real object is difficult to set up
- real object has behavior that is hard to cause (e.g., network error) (similar to 1)
- real object is slow
- real object has (or is) a UI
- test needs to query the object, but the queries are not available in the real object (e.g., "was this callback called?") (This needs a Mock Object that has *more* stuff than the real object; the other cases usually require a stub that is far smaller than the real object).
- real object acts "normal" most of the time, but once a month (or even less often) it does something "exceptional". We want Unit Tests to make sure the rest of the system does the Right Thing whether or not the object is acting "normal" or "exceptional". (Is this the same as #2 ?)
- real object does not yet exist
Mock framework:
Commonly used Mock Frameworks:
- NSubstitute: Perfect for those new to testing, and for others who would just like to to get their tests written with less noise and fewer lambdas.
- Rhino Mocks: Open Source! Rhino Mocks is a dynamic mock object framework for the .Net platform. Its purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing.
- TypeMock: Commercial product which among other supports the following features: Auto-runner for immediate feedback of newly introduced bugs, Failed test analyzer pinpoints bugs, Visual coverage indication shows code coverage, Test auto-completion, Mocking on steroids lets you test any code
- EasyMock.NET: EasyMock.NET is a class library that provides an easy way to use mock objects for given interfaces or remote objects. EasyMock.NET is a port of the EasyMock framework, which can be found for the Java(TM) platform.
- NMock: NMock is a dynamic mock object library for .NET. Mock objects make it easier to test single components—often single classes—without relying on real implementations of all of the other components. This means we can test just one class, rather than a whole tree of objects, and can pinpoint bugs much more clearly. Mock objects are often used during Test Driven Development.
- FakeItEasy: A .Net dynamic fake framework for creating all types of fake objects, mocks, stubs etc. Recently is getting more traction as it makes extremely simple to create mocking objects.
- MOQ:
Moq (pronounced “Mock-you” or just “Mock”) is a mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn’t require any prior knowledge or experience with mocking concepts.
--------------------------------------------------------------------------------------
1. MOQ: (http://code.google.com/p/moq/wiki/QuickStart)
What is Moq
Moq (pronounced “Mock-you” or just “Mock”) is a mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn’t require any prior knowledge or experience with mocking concepts.Moq is intended to be simple to use, strong typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).
Authors of Moq called it The simples mocking library for .NET and Silverlight. I am not fully sure if it is the simplest but I may confirm that is really simple and powerful which is why I particularily like using Moq.
You may define mocks for the following:
- Object Methods
- Properties
- Events
- Callbacks
- Verifications
- Some more advanced scenarios like verification and Implementation of different interfaces
Installation
There are two ways of installing Moq, either by using NuGet plugin for Visual Studio or by installing it manually. Just type Moq in NuGet and you will get the mocking library. Just keep in mind that nuget will install by the default the version for the framework you are currently using (3.5, 4, etc..)If you want to install it manually, just download the library from the official website and reference it from your project.
System Under Test
After this short background about mocking and the Moq library itself, let’s see some code:The following will be our base code which will be tested:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class CustomerService { private ICustomerRepository _repository; public CustomerService(ICustomerRepository repository) { _repository = repository; } public Customer GetCustomer( int id) { return _repository.GetCustomer(id); } } public interface ICustomerRepository { Customer GetCustomer( int id); } public class Customer { public string LastName { get ; set ; } public string FirstName { get ; set ; } } |
CustomerService
that as a dependency
has the ICustomerRepository
that act as an interface to a class
that would for instance return customer data from a database. I’ve omitted the
implementation of this interface as this is going to be a object that we are
going to mock, as we don’t really want to go to the database and retrieve
Customer
data. As mentioned before, the test has to be
deterministic and fast. A simple test
With our first test we are going to create a mock that would represent theICustomerRepository
and set up the expectations. Expectation could
represent two things: What the method should receive as input parameters, and
what will the method return back as a result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
[TestMethod] public void GetCustomer_ValidId() { //-- 1. Arrange ---------------------- const int CUSTOMER_ID = 1; const string FNAME = "John" ; const string LNAME = "Doe" ; //-- Creating a fake ICustomerRepository object var repository = new Mock(); //-- Setting up the repository in order to return //-- exactly what we expect. repository .Setup(m => m.GetCustomer(CUSTOMER_ID)) .Returns( new Customer { FirstName = FNAME, LastName = LNAME }); var service = new CustomerService(repository.Object); //-- 2. Act ---------------------- var customer = service.GetCustomer(CUSTOMER_ID); //-- Assert ---------------------- Assert.IsTrue(customer != null ); Assert.IsTrue(customer.FirstName == FNAME); Assert.IsTrue(customer.LastName == LNAME); } |
1
|
var repository = new Mock(); |
ICustomerRepository
interface.on the other hand, Moq uses a very simple notation which is as follows
1
2
3
|
repository .Setup(m => m.GetCustomer(CUSTOMER_ID)) .Returns( new Customer { FirstName = FNAME, LastName = LNAME }); |
- By using the
Setup
method, by passing a lambda expression, defines the method we want to test and the expected input parameter. In our case, the test will fail if the input parameter passed at the runtime will not be equal to what we have defined in the Setup. The input parameter has to be equal to CUSTOMER_ID in our case.
There is a possibility to use as wellIt.IsAny()
to say, that we don’t really care what the input parameter contains , but it has to be of typeint
. - By using the
Returns
method, defines the return data, which is, what is returned at the runtime when the test get’s executed.
1
2
3
4
5
6
7
8
9
10
11
|
public class SomeClassName: ICustomerRepository { public Customer GetCustomer( int id) { return new Customer { FirstName = "John" , LastName = "Doe" } } } |
ICustomerRepository
interface and contains some “hardcoded” values that will be returned. Instead of
using Moq (or any other mocking framework) we could write this manually but
using the framework simplifies it drastically.2. Rhino Mock:
Rhino Mocks is a dynamic mock object framework for the .Net platform. Its purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing.Rhino Mocks objects allows Expectations, Constraints and Callbacks to be setup, specifying how the tested object should interact with the mocked object. These conditions are evaluated throughout the test run, and fails early in order to give you a warning as localizable as possible.
Rhino.Mocks features:
- Supports several models of placing conditions on the mocked objects, all of which are verified on the fly during test execution. This allows testing the interactions between objects and fails as soon as the test deviates from the specified conditions. This has the advantage of giving the exact point of failure.
- Mocked implementations of the objects are generated on the fly which avoids a code generation during builds.
- Clear error messages for failing conditions.
- Flexible way to specify conditions using Expectations, Constraints and Callbacks which is type safe and easily refactorable by the current tools.
- Currently works only on interfaces and classes which inherit MarshelByRef.
Here is how Rhino Mocks would handle the previous tests:
[Test]
public void RenterPaysForCar ()
{
MockControl mockCar= MockControl.CreateControl(typeof(ICar));
MockControl mockPerson = MockControl.CreateControl(typeof(IPerson));
ICar car = controlCar.GetMock() as ICar;
IPerson person = controlPerson.GetMock() as IPerson;
mockCar.ExpectAndReturn(car.CurrentPrice, 115);
mockCar.ExpectAndReturn(car.RentedFrom,DateTime.Now.AddDays(-7));
mockCar.ExpectAndReturn(car.RentedBy,person);
ICarRental avis= new AvisCarRental();
mockCar.SetupResult(car.ReturnToParkingLot(avis))
mockCar.Callback = new
CarRentalDelegate(InformReachedParkingLot); person.Pay(avis,850);
avis.ReturnCar(car);
controlCar.Verify();
controlPerson.Verify();
}
delegate void CarRentalDelegatE(ICarRental carRental);void InformReachedParkingLot(ICarRental carRental)
{//assumes that car is an instance variable, not a local variable in the test
carRental.CarInParkingLot(car);
}
In this case, it's not much of a difference, that is because we are using expectations), the same way EasyMock.Net works. Let's try something more difficult, let's assume that when the car rental sends the car to its parking lot, they require the car to inform that it arrived safely before letting the renter go. In essence, classic threading problem, but one that is very hard to solve using NMock. I created a couple of hacks in order to solve. Usually the solution for those kinds of problem is to write your own test class. This isn't very practical[5] for large number of classes, here is how I would solve this using Rhino Mocks, I'll leave you implementing the same with the other framework.
You can see that we set up a callback for ReturnToParkingLot, and using that callback we get the ICarRental reference that we got. So we can do call the CarInParkingLot() andreturn from ReturnCar() method.
Another way to specify conditions is to use constraints, they are used in much the same way as they are in NMock:
car.AddGas(0);
mockCar.Constraints(new IsEqualOrLessThan(150));
The Last Method concept:
Most actions in Rhino.Mocks are done on the last method call, after each call, you can setup more information about the call: Return value, if and what to throw, constraints and callbacks. You set these conditions by calling the methods on the MockControl (Returns, Throws, Constraints and Callback). Most methods has overloads that allows you to setup returning or throwing for multiply calls of the same method. Rhino.Mocks ensure that all the requirements of a method are satisfied before the next method can be recorded, this means that for methods that return values, a return value or an exception to throw need to be set. You can setup several behaviors for a single method. The same method but with different arguments mean a different method call, as far as Rhino.Mocks is interested.
Return Value:
A method that returns a value must define either Returns or Throws or their equivalents ( ReturnsFor(), ThrowsFor(), AlwaysReturns, AlwaysThrow, SetupResult() or ExpectAndReturn() ).
Tips & Tricks:
- If you want just a stub, you can use MockControl.CreateNiceControl(), which will not throw on unexpected calls, and would always return the default value. (Null or zero, usually).
- If you want to check the ordering of the calls, using MockContrl.CreateStrictControl().
- To mock a get property, you need code similar to the one below, it's easier and more readable to use the convenience methods (see separate section);
Callbacks:
A callback need to match the last method signature, but is free to have a different return type (or no return type, of course). The return value of the callback is ignored, so don't expect to return some value from the callback and get it from the mocked method. This is by design and is meant to reduce the chance that the callbacks will be abused.
Mocking Classes:
Rhino.Mocks can mock classes if they inherit from MarhsalByRef, it's not a recommended approach. Use of interfaces is highly recommended.
Gotcha:
- A method call is consider equal to another if they are the same method with the exact same arguments. This means that something("foo") and something("bar") are not considered to be the same method.
- Validating a method call and expecting a method call are two distinct subjects. A call is validated (using expectations, constraints or callbacks) only if the call is expected. You can setup the number of expected calls using the ReturnsFor(), CalledFor() and ThrowsFor() methods.
- Callback will be called for each invocation of the method, and all validation relies on whatever or not the callback throws. If the callback does not throw, the method is considered validated.
- The return value of callbacks is ignored, the only way to set up a return value is to use the Returns derivatives, or the convenience methods for them.
- Don't forget to call the Replay() methods
Expect Call
To create any mock object you need to create instance of MockRepository Class which act as project presenter.
I am taking very simple example how to create mock object and set expectation on property.
01.
[TestMethod]
02.
03.
public
void
TestMethod2()
04.
{
05.
//Testing with Mock Object
06.
MockRepository repo =
new
MockRepository();
07.
TestClassForMockTesting obj = repo.CreateMock();
08.
Expect.Call(obj.Message).Return(
"hello"
);
09.
repo.ReplayAll();
10.
Assert.AreEqual(
"hello"
, obj.Message);
11.
repo.VerifyAll();
12.
}
13.
public
class
TestClassForMockTesting
14.
{
15.
public
TestClassForMockTesting() { }
16.
public
string
Message
17.
{
18.
get
19.
{
20.
return
Guid.NewGuid().ToString();
21.
}
22.
}
23.
}
Output
Above code will raise exception : "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)." because any expect call can only set values for Virtual methods or properties. If you make Messageproperty as virtual then mock framework will set Message value as “Hello” instead on GUID which can’t be predicated on every call. if you do same test with real object it will always because you can’t return values.So if we make Message property as Virtual this test will pass.
Expect call for DbConnection and void method
this example test dbconnection open method. First we create mock dbconnection and inject dbconnection object through constructor as we know that without database connection string real database connection object will raise exception on calling Open method.On thing note here to expect call void method we have to use anonymous delegate in Expect.Call method.
If you don't call this statement Expect.Call(delegate {
mockConn.Open(); }) test will fail and will give error like

Test DataAccess Layer’s Method
This example shows how can we mock database connection and test our unit test. Expect.Call(obj.GetHotel(2)).Return(h).Repeat.Twice() this line tells same expectation twice because obj.GetHotel(2) statement is using two times.
References:
http://www.ayende.com/wiki/Rhino+Mocks+Documentation.ashx
Syntax Examples: http://www.ayende.com
/wiki/GetFile.aspx?File=Rhino+Mocks+3.3+Quick+Reference.pdf
Above code will raise exception : "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)." because any expect call can only set values for Virtual methods or properties. If you make Messageproperty as virtual then mock framework will set Message value as “Hello” instead on GUID which can’t be predicated on every call. if you do same test with real object it will always because you can’t return values.So if we make Message property as Virtual this test will pass.
1.
public
virtual
string
Message {
get
{
return
Guid.NewGuid().ToString(); }
}
this example test dbconnection open method. First we create mock dbconnection and inject dbconnection object through constructor as we know that without database connection string real database connection object will raise exception on calling Open method.On thing note here to expect call void method we have to use anonymous delegate in Expect.Call method.
01.
[TestMethod]
02.
public
void
TestDbConnection()
03.
{
04.
//Testing with Mock Object
05.
MockRepository repo =
new
MockRepository();
06.
IDbConnection mockConn = repo.CreateMock();
07.
TestClassForMockTesting obj =
repo.CreateMock(mockConn);
08.
//Expecting void methods
09.
Expect.Call(
delegate
{ mockConn.Open(); });
10.
repo.ReplayAll();
11.
Assert.IsTrue(obj.openConnection());
12.
repo.VerifyAll();
13.
}
14.
public
class
TestClassForMockTesting
15.
{
16.
public
TestClassForMockTesting()
17.
{
18.
}
19.
//constructor for injecting Mock DbConnection
20.
public
TestClassForMockTesting(IDbConnection conn)
21.
{
22.
_conn = conn;
23.
}
24.
IDbConnection _conn;
25.
public
virtual
string
Message {
get
{
return
Guid.NewGuid().ToString(); } }
26.
public
bool
openConnection()
27.
{
28.
try
29.
{
30.
_conn.Open();
31.
return
true
;
32.
}
33.
catch
(Exception ex)
34.
{
35.
return
false
;
36.
}
37.
}
38.
}

Test DataAccess Layer’s Method
This example shows how can we mock database connection and test our unit test. Expect.Call(obj.GetHotel(2)).Return(h).Repeat.Twice() this line tells same expectation twice because obj.GetHotel(2) statement is using two times.
01.
public
void
TestGetHotels()
02.
{
03.
//Testing with Mock Object
04.
MockRepository repo =
new
MockRepository();
05.
IDbConnection mockConn = repo.CreateMock();
06.
ITestClassForMockTesting obj = repo.CreateMock();
07.
obj.DBConn = mockConn;
08.
//Expecting void methods
09.
Hotel h =
new
Hotel();
10.
h.Name =
"Taj"
;
11.
h.Id = 3;
12.
13.
Expect.Call(obj.GetHotel(2)).Return(h).Repeat.Twice();
14.
15.
repo.ReplayAll();
16.
Assert.AreEqual(
"Taj"
, obj.GetHotel(2).Name);
17.
Assert.AreEqual(3, obj.GetHotel(2).Id);
18.
19.
repo.VerifyAll();
20.
}
21.
public
class
TestClassForMockTesting : MyVacations.Tests.ITestClassForMockTesting
22.
{
23.
public
TestClassForMockTesting()
24.
{
25.
26.
}
27.
public
IDbConnection
DBConn {
set
{ _conn =
value; } }
28.
//constructor for injecting Mock DbConnection
29.
30.
IDbConnection _conn;
31.
public
virtual
string
Message {
get
{
return
Guid.NewGuid().ToString(); } }
32.
public
bool
openConnection()
33.
{
34.
try
35.
{
36.
_conn.Open();
37.
return
true
;
38.
}
39.
catch
(Exception ex)
40.
{
41.
return
false
;
42.
}
43.
44.
}
45.
46.
public
Hotel
GetHotel(
int
hotelId)
47.
{
48.
List lst =
new
List();
49.
DataSet ds =
new
DataSet();
50.
IDbDataAdapter odp =
new
SqlDataAdapter();
51.
IDbCommand cmd =
new
SqlCommand(
"select * from hotel where hotelid ="
+
hotelId.ToString());
52.
53.
odp.SelectCommand = cmd;
54.
odp.SelectCommand.Connection = _conn;
55.
odp.Fill(ds);
56.
DataRow row = ds.Tables[0].Rows[0];
57.
58.
Hotel h =
new
Hotel();
59.
h.Id = Convert.ToInt32(row[
"Id"
]);
60.
h.Name = row[
"Name"
].ToString();
61.
62.
return
h;
63.
}
64.
}
Syntax Examples: http://www.ayende.com
/wiki/GetFile.aspx?File=Rhino+Mocks+3.3+Quick+Reference.pdf
--------------------------------------------
Rhino Mocks vs Moq
I’ve heard multiple people state that they prefer Moq over Rhino Mocks because the Rhino Mocks syntax isn’t as clean. And while I don’t have a strong preference between the two, I’d like to help dispel that myth. It is true that, if you choose the wrong syntax, Rhino can be more complicated. This is because Rhino has been around for a while and it’s original syntax pre-dates the improved Arrange/Act/Assert syntax. I go into a lot more detail on Rhino Mocks and the appropriate way to use it , but to dispel the myth that Rhino Mocks is complicated I would like to compare the syntax for creating stubs and mocks using Rhino vs. Moq:
Moq Syntax:
//Arrange var mockUserRepository= new Mock(); var classUnderTest = new ClassToTest(mockUserRepository.object); mockUserRepository .Setup(x => x.GetUserByName("user-name")) .Returns(new User()); //Act classUnderTest.MethodUnderTest(); //Assert mockUserRepository .Verify(x => x.GetUserByName("user-name"));Rhino Stub Syntax:
//Arrange var mockUserRepository=MockRepository.GenerateMock(); var classUnderTest = new ClassToTest(mockUserRepository); mockUserRepository .Stub(x => x.GetUserByName("user-name")) .Returns(new User()); //Act classUnderTest.MethodUnderTest(); //Assert mockUserRepository .AssertWasCalled(x => x.GetUserByName("user-name"));Notice that there are only four differences in those examples: the use of “new Mock” instead of MockRepository, the term Setup vs. Stub and the term Verify vs. AssertWasCalled and the need to call “.Object” on the mock object when using Moq. So why do so many people think Rhino Mocks more complicated? Because of it’s older Record/Replay syntax which required code like the following:
using ( mocks.Record() ) { Expect .Call( mockUserRepository.GetUserByName("user-name) ) .Returns( new User() ); } using ( mocks.Playback() ) { var classUnderTest = new ClassUnderTest(mockUserRepository); classUnderTest.TestMethod(); }There is also another benefit of using Rhino Mocks. The support for Rhino by StructureMap AutoMocker is cleaner due to the fact that the mocks returned by Rhino are actual implementations of the interface being mocked rather than a wrapper around the implementation which is what Moq provides. AutoMocker allows you to abstract away the construction of the class under test so that your tests aren’t coupled to the constructors of the class under test. This reduces refactoring tension when new dependencies are added to your classes. It also cleans up your tests a bit when you have a number of dependencies. If you haven’t used AutoMocker, you can quickly learn how it works by checking out the AutoMocker module in Pluralsight Rhino Mocks video. But here is a quick comparison of using AutoMocker with Moq vs. Rhino:
Moq syntax using MoqAutoMocker:
//Arrange var autoMocker = new MoqAutoMocker(); Mock.Get(autoMocker.Get()) .Setup(x => x.GetUserByName("user-name")) .Returns(new User()); //Act autoMocker.ClassUnderTest.MethodUnderTest(); //Assert Mock.Get(autoMocker.Get()) .Verify(x => x.GetUserByName("user-name"));Rhino syntax using RhinoAutoMocker:
//Arrange var autoMocker = new RhinoAutoMocker(); autoMocker.Get(); .Setup(x => x.GetUserByName("user-name")) .Returns(new User()); //Act autoMocker.ClassUnderTest.MethodUnderTest(); //Assert autoMocker.Get(); .AssertWasCalled(x => x.GetUserByName("user-name"));I hope that this clarifies, for some, the correct way to use Rhino Mocks and illustrates that it is every bit as simple as Moq when used correctly.
I have to say, I did prefer Moq slightly to Rhino Mocks. The newer Arrange, Act, Assert (AAA) style syntax in Rhino Mocks is a huge improvement over the old Record/Replay mess. But Moq has the benefit of being born at the right time and has AAA style calls without the burden of supporting deprecated syntax. This means Moq has cleaner documentation, fewer options, and fewer ways to get confused by the API. I really couldn’t find anything I needed to do in Moq that I couldn’t do. I did get a little tripped up having to get the object out of the mock, with myMock.Object calls, but that wasn’t a big deal.
Here’s the NuGet Moq install package syntax to add Moq to your unit test project:
