NMock2 Documentation


NMock2 is a library for assisting test driven development of .NET code by providing a dynamic Mock Object framework for .NET interfaces.

Notes About This Documentation

Typical Scenario

A typical test that uses NMock2 looks like this:

public class TypicalTest
    private Mockery mockery;
    private IDependency dependency;
    private Testee testee;

    public void SetUp()
        mockery = new Mockery();

        dependency = mockery.NewMock<IDependency>();

        testee = new Testee(dependency);

    public void CallMethodOnDependecy()
        Expect.Once.On(dependency).Method("Add").With(2, 3).Will(Return.Value(5));

        int result = testee.Add(2, 3);

        Assert.AreEqual(5, result, "wrong result was returned.");

In the SetUp method we define the mockery that is used to create dynamic mocks, mocks for all dependencies of the class under test and an instance of the class under test (= testee).

The test method you see in this sample checks that the method Add works correctly.

In the test method we first define the expectations we have. In our scenario this means that we expect that the method Add is called on the dependency with parameters 2 and 3. Furthermore we define how the mock should react on a call to the method Add (return 5 as method return value).

Then we execute the method on the testee that we want to test.

Afterwards, we check that the value that was returned matches our expectation with an NUnit assert command.

Finally, we check that the testee really called the method on the dependency and did not just fake the wanted behaviour be just returning a constant. The VerifyAllExpectationsHaveBeenMet method checks that all expectations we defined were met.