Best Practices, Mock Usage Pattern

There are a few ways that mocks can be used. As many of you who read my blog might guess I am not an OO Purist. I think that I am more of a Pragmatic OO. The same goes with unit tests, I don’t strongly believe that there must be one Assert per test, and I see many tests that verify the interaction and state in the same test.

But here are a few things to remember:

  1. You should Verify the Mocks between tests
    This will allow the tests to fail if an expectation was not met
  2. If your test fails (an exception thrown) you still need to clear your expectations
    Otherwise you will leave fake behavior for the next test

Here is a pattern that will solve these issues.

/// <summary> /// This is the best practice tests with TypeMocks /// </summary> [TestFixture] public class MyTests { /// <summary> /// Clear mocks /// </summary> [TearDown] public void CleanUp() { MockManager.ClearAll(); } /// <summary> /// We will test with mocking /// </summary> [Test] public void TestWithMock() { // setup mock // run test // optional assert Assert.AreEqual(); // Verify mocks MockManager.Verify(); } }
2 comments
  1. Is there any particular reason that you are calling Verify() in the test? I have defaulted (perhaps wrongly) to putting all of my mock management calls into the SetUp and TearDown methods. If a test is run that does not use mocking then I am out a small bit of performance, but it is handy. It also allows me to refactor my tests more easily. Below is what I try to start with when testing a class with mocks.


    [TestFixture]
    public class MyTests {
    #region Setup/tear down

    [TestFixtureSetUp]
    public void InitTestFixture() {
    }

    [TestFixtureTearDown]
    public void CleanUpTestFixture() {
    }

    [SetUp]
    public void InitTest() {
    MockManager.Init();
    }

    [TearDown]
    public void CleanUpTest() {
    MockManager.Verify();
    MockManager.ClearAll();
    }

    #endregion
    }

  2. Ian,
    There are a few reasons to put Verify in the test method:
    1. In those cases where the test throws some kind of exception. The TearDown will run a Verify and you will see many failures that will make it harder to find the real problem.
    2. Since NUnit 2.2, all failures in the TearDown are ugly, with big call stacks making it harder to understand.

    Note: There is no reason to call ClearAll right after Verify, because Verify clears all the mocks too. The reason that ClearAll is called in the TearDown are for those cases where the tests throws an exception.

Add Comment

Required fields are marked *. Your email address will not be published.