We as humans don’t liked to be mocked. Severe mocking can even make us cry. But in software development especially in unit testing mocking plays a very important role. In other words you can release your inner desires of mocking when writing unit tests. In this post I will explain how mocking a help you to improve your unit tests and also how mocking can help to keep your tests independent.
I will focus on a real world example so that you will get a good grasp of mocking. Let’s say we are working on a banking software which pulls out the customer balance information from some database. The software also makes a request to an external web service for authentication. The process of authentication is a little slow since it involves many different steps. We want to test that if the customer balance returned is correct or not.
Here is our web service with the Authenticate method:
public class AverageJoeBankService : IAverageJoeBankService
{
public bool Authenticate(string userName, string password)
{
// This is just simulate the time taken for the web service to authenticate!
System.Threading.Thread.Sleep(5000);
return true;
}
}
As, you can see I am simply simulating the Authenticate method. We are assuming that it will take at least 5 seconds to authenticate the user.
And here is the AccountBalanceService method:
public class AccountBalanceService
{
private IAverageJoeBankService _averageJoeService;
public AccountBalanceService(IAverageJoeBankService averageJoeService)
{
_averageJoeService = averageJoeService;
}
public double GetAccountBalanceByUser(User user)
{
// the authenticate method below takes too much time!
bool isAuthenticated = _averageJoeService.Authenticate(user.UserName, user.Password);
if (!isAuthenticated)
throw new SecurityException("User is not authenticated");
// access database using username and get the balance
return 100;
}
}
Here is our first attempt to write the unit tests:
[Test]
public void should_be_able_to_get_the_balance_successfully_without_using_mock_objects()
{
User user = new User();
user.UserName = "johndoe";
user.Password = "johnpassword";
_accountBalanceService = new AccountBalanceService(new AverageJoeBankService());
Assert.AreEqual(100, _accountBalanceService.GetAccountBalanceByUser(user));
}
In the unit test above I am simply using the concrete implementation of the AccountBalanceService class which triggers the actual method for authentication.
When you run your tests you will get the following result:

The test passed and you have a big smile on your face. Not so fast joy boy! Take a look at the time it took to run the test 6.69 seconds. That is too much time to run a single test. Apart from time there are other problems with the test. The test is dependent on the AverageJoeBankService. If the web service is not available then the test will fail. Unit tests should be independent and they should run fast. Let’s make this test faster by introducing mock objects.
Oh wait! I haven’t explained what mock objects mean in the context of unit tests. Mock objects are like real objects but they don’t do anything. I know the definition I just gave you is kind of crazy but you will know what I am talking about in a minute.
Here is the unit test which uses mock objects:
private AccountBalanceService _accountBalanceService;
private MockRepository _mocks;
[SetUp]
public void initialize()
{
_mocks = new MockRepository();
}
[Test]
public void should_be_able_to_get_the_balance_successfully()
{
User user = new User();
user.UserName = "JohnDoe";
user.Password = "JohnPassword";
var averageJoeService = _mocks.DynamicMock<IAverageJoeBankService>();
_accountBalanceService = new AccountBalanceService(averageJoeService);
using (_mocks.Record())
{
SetupResult.For(averageJoeService.Authenticate(null, null)).IgnoreArguments().Return(true);
}
using (_mocks.Playback())
{
Assert.AreEqual(100,_accountBalanceService.GetAccountBalanceByUser(user));
}
}
First, we created the MockRepository which is part of the Rhino Mocks frameworks. You might say “What the hell is Rhino Mocks?” Rhino mock is a mocking framework which provides you different features and ways to mock your objects. There are several other mocking frameworks which include NMock, NMock2, TypeMock, MoQ.
Amway, in the unit test above I am creating a mock object using the following code:
var averageJoeService = _mocks.DynamicMock<IAverageJoeBankService>();
_accountBalanceService = new AccountBalanceService(averageJoeService);
After passing the mocked AverageJoeService (Not the real service) to the AccountBalanceService I put my expectations.
using (_mocks.Record())
{
SetupResult.For(averageJoeService.Authenticate(null, null)).IgnoreArguments().Return(true);
}
This means that when the averageJoeService.Authenticate method is fired then return me true so I can proceed further. You can also see that I am not concerned about the passed in arguments and that’s why I am using IgnoreArguments.
The next part is the Playback which is the code that will trigger the expectations and produce the desired result. Here is the Playback part:
using (_mocks.Playback())
{
Assert.AreEqual(100,_accountBalanceService.GetAccountBalanceByUser(user));
}
Here is the output of the unit test:

Now the unit test will only takes 1.81 seconds. Not only the test is faster but now it is not dependent on the AverageJoeBankService. This means that even if the web service down you will be able to run the above test.
If you are interested in watching a complete screencast of the same scenario then visit the following link:
Introduction to Mocking
Download Sample