NUnit: Using Mock Objects

Summary

A mock object is simply a testing replacement for a real-world object.

A mock object is simply an object that implements a particular interface, returns values we want it to return, and checks that it was used in a certain way.

There are a number of situations that come up where mock objects can be useful, including:

  • The real object produces unpredictable results
  • The real object is difficult to set up, like requiring a certain file system, database, or network environment
  • The real object has behaviour that is hard to trigger (for example, a network error)
  • The real object is slow
  • The real object has (or is) a user interface
  • The real object does not yet exist

We need to stub out, or fake, all those uncooperative parts of the real world. In many cases, stubs just implement an interface and return dummy values for the methods in that interface.

First extract an interface for the methods we need to stub and apply that interface to the class we want to mock.

Then return the dummy value that we think will evoke the behaviour we want. Sometimes we need to do more than return dummy values to get at the code we're trying to test.

NUnit includes its own built-in framework that the NUnit team uses to test NUnit itself. However, NUnit's mock framework doesn't provide all of the features of some other frameworks. To use, add a reference to the nunit.mocks.dll assembly.

Recommend using NMock or RhinoMock frameworks for standard mock program-activities, and DotNetMock for when you need to mock one of the messier framework classes.