NMock

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.

NMock 2.0 Release Candidate 2 is now available! The original NMock was a .NET port of the Java-based DynaMock, whereas NMock 2.0 is inspired by the newer jMock library. Expectations are defined using a much more “conversational” style, including plenty of syntactic sugar to improve clarity.

A dynamic mock object:

  • takes on the interface of another object, allowing it to be substituted for a real one for testing purposes.
  • allows expectations to be defined, specifying how the class under test is expected to interact with the mock.
  • fails the test if any of the expectations are violated.
  • can also act as a stub, allowing the test to specify objects to be returned from mocked methods.

Features specific to NMock:

  • expectations are specified beforehand and verified on the fly as the code under test is being executed, rather than afterwards using assertions. This has the advantage that mocks fail fast, allowing you to easily pinpoint the exact point the test failed, using a stack trace or debugger.
  • mock implementations of interfaces are generated on the fly at runtime, which avoids having to add a code generation step to the build.
  • error messages clearly show the reason for the failure.
  • flexible expectations can be built up using the constraint library.