As many would know, mocking is a useful and inevitable part of unit testing. The intention behind mocking of objects is to isolate the functionality of one method from its dependencies, For e.g. a method call from within the target test method being handled in an external interface.
This approach will help us focus on the unit being tested, rather than arranging for dependency invocation (which might be really complex at times).
I would like to share a basic tutorial here on mocking .net objects using NMock2 (available at http://nmock.org)
Steps to be followed are as follows.
1) Download the NMock2 package from http://nmock.org/download.html
2) Create a console application and add NMock2.dll from the downloaded package, as a reference.
3) Consider that you have a simple interface defined as follows.
public interface IPerson { string GetName(); }
4) A class Hello has the following definition
class Hello { IPerson person;
//--This method invokes the interface method.
public String Greet()
{
return "Hello " + person.GetName();
//If you were to write a ut for this method (without nmocks), you should have created an
//actual object of person and your inputs should be capable of navigating
//thru' GetName() of Person class
}
}
5) Our intention is to unit test the method Hello.Greet(). This is not straight forward as definition of IPerson.GetName() is not known. Moreover, it should not be of our concern when we are testing Greet() method’s functionality.
6) This is where we mock the Interface IPerson and hardcode a return value for the method GetName() so as to concentrate on the functionality of the method Greet() alone while testing. Let us see how we can do that.
7) We create a test case class, say HelloTestCases and write a method to test Greet()
i) Make use of a class named Mockery (supplied by NMock2) to create a mock object.
ii) Create a mocked interface object for IPerson using the NewMock() method.
iii) Set up a mocked result for any method/property by hardcoding of your choice.
iv) Mock the result for one execution of the mocked method.
v) Create an object of the target test class.
vi) Invoke the target test method using the object instance created in (v) and check the results with Assert statements of NUnit.
public void Test_GreetPositive() { //--i. Creating a mockery object. Mockery personMock = new Mockery(); //--ii. Mocking the IPerson interface using Mockery object. IPerson p = personMock.NewMock<IPerson>(); //--iii. Setting the mocked return value. string returnValue = "Pradeep"; //--iv. Mocking the result for method call IPerson.GetName() method. Expect.Once.On(p).Method("GetName").WithNoArguments().Will(Return.Value(returnValue)); //--v. Creating the target class object. Hello h = new Hello(p); //--vi. Invoking the target test method. Assert.AreEqual("Hello Pradeep",h.Greet()); }
So simple, isn’t it? This was a simple example. There is much more to add as feathers to NMock2.
NMock2 also provides a wide variety of Expectatons, like,
Expect.Once, Expect.Excatly(<number of times a method is called>), Stub (0 or many times), Expect.Never and so on. You could also expect exceptions by adding an attribute called [ExpectedException(typeof(<exception class>)] before the unit test method for the target method that throws an exception. In other words, NMocks2 is really an awesome lib to do a perfect unit test for your libraries. Try it out and share your experiences.
Thanks! See you all soon.
Praseo

If you want to have a look at the latest and greatest NMock2 then please go to http://sourceforge.net/projects/nmock2. The one with the 2 in its name.
The version on the nmock site (which is not under our control, unfortunately) is not maintained anymore.
Happy mocking
Urs
Hello, Praseo:
I am a little bit confused about your sample code:
Hello h = new Hello(p);
Will the compiler complain Hello takes no argument? Could you provide a sample so we can download?
Thanks,
John L.
Hello John
You have to add a constructor in the class hello:
public Hello(IPerson person)
{
this.person = person;
}
The mock interceptor that was created in step iv will create the GetName() output.
If you do not use nUnit, you can use instead of Assert.AreEqual for the verification in step vi:
Debug.Assert(“Hello Pradeep”==h.Greet());
This is really a very good article. Thanks a lot.
John
/* **************************************************
* Test program for NMock2
*
* The fragments form http://www.nmock.org/quickstart.html were used as input
* and built together to a complete sample program that is ready to be used
*
* nUnit Code was eliminated
*
* Author: Roger Wissmann
* *********************************************** */
using System;
using System.Diagnostics; // Assert
using NMock2; // Nmock stuff
namespace NMock
{
///
/// Account-Definition—————–
///
public class Account
{
private string m_ID;
private double m_Amount;
private string m_Currency;
public Account(string id, string currency)
{
m_ID = id;
m_Amount = 0;
m_Currency = currency;
}
public void Withdraw(double money)
{
m_Amount -= money;
}
public void Deposit(double money)
{
m_Amount += money;
}
public double Balance
{
get { return m_Amount; }
}
public string Currency
{
get { return m_Currency; }
}
}
/// End of Account Definition ————-
public class Sample2
{
///
/// Interface Definition for the Currency Services
///
public interface ICurrencyService
{
double GetConversionRate(string fromCurrency, string toCurrency);
}
// The implementation for the interface ICurrencyService is missing by intention
// -> data will be provided by the mock
///
/// Interface-Definition for the Account Services
///
public interface IAccountService
{
void TransferFunds(Account from, Account to, double amount);
}
public class AccountService : IAccountService
{
ICurrencyService m_CurrencyService;
// Constructor
public AccountService(ICurrencyService currencyService)
{
m_CurrencyService = currencyService;
}
public void TransferFundsStraight(Account from, Account to, double amount)
{
from.Withdraw(amount);
to.Deposit(amount);
}
public void TransferFunds(Account from, Account to, double amount)
{
from.Withdraw(amount);
double conversionRate = m_CurrencyService.GetConversionRate(from.Currency, to.Currency);
double convertedAmount = amount * conversionRate;
to.Deposit(convertedAmount);
}
}
///
/// Test
///
public class Tests
{
public void Test_TransferFunds()
{
Mockery myMock = new Mockery();
// initialisiere Mock für das ICurrencyService-Interface
ICurrencyService m_MockCurrencyService = myMock.NewMock();
AccountService m_AccountService = new AccountService(m_MockCurrencyService);
Account canadianAccount = new Account(“12345″, “CAD”);
Account britishAccount = new Account(“54321″, “GBP”);
britishAccount.Deposit(100);
Expect.Once.On(m_MockCurrencyService).
Method(“GetConversionRate”).
With(“GBP”, “CAD”).
Will(Return.Value(2.20));
m_AccountService.TransferFunds(britishAccount, canadianAccount, 100);
// This tests might fail because of float-problems
Debug.Assert(0 == britishAccount.Balance);
Debug.Assert(220 == canadianAccount.Balance);
myMock.VerifyAllExpectationsHaveBeenMet();
}
}
}
}