Dealing with Dependencies in Test-Driven Development through Mocking

Mocking is generally an overloaded term. But at its base, it's about changing behavior -- specifically, dependency behavior.

I'm a big fan of Test Driven Development (TDD); but I've discovered that some things are easy to unit test (e.g. interfaces, objects) and some things are hard. Dependencies between classes create problems -- if the class I'm testing class creates and uses some object, the validity of my test is compromised. If my test fails, have I proven that the class I'm testing has a problem? Or have I proved that the object the class calls has a problem?

I asked Gil Zilberfeld, a Product Manager for TypeMock, for some advice. Gil has more than 15 years of experience in software development, from coding to team management and process implementation. Here's what he said about solving my problems with Mocking.

Mocking is generally an overloaded term. But at its base, it's about changing behavior -- specifically, dependency behavior. Working with MSMQ was my first mock object.

I needed to write to a queue. This was the first version of the method I wanted to test:

 public class RealMessageQueue : IMessageQueue
  {
    var queue = MessageQueue.Create("AnyQueue");

    public void Send(object message)
    {
        queue.Send(message);
    }
  }

My test for that method looked like this:

[TestMethod]
  public void Send_StringMessage_MessageWasSent()
  {
    var messageQueue = new MessageQueue();
    Server.SendMessage(messageQueue, "message");
  }

This isn't a great test; it only fails if the method blows up. So I added some code to read the message back from the queue to make sure that the message had arrived. But queues (which is the dependency of Server, in this case) sometimes behave funny. And we don't like funny, we like dependable. In this case, the message did arrive -- sort of. Because MSMQ has an (asynchronous) mind of its own, sometimes the message arrived before the test ended (success) and sometimes after (failure).

I couldn't control the queue's behavior, so I had to replace it with another object—a mock object—that I could control. So I changed the signature of my SendMessage method a bit:

public class Server
  {
    public void SendMessage(IMessageQueue queue, object message)
    {
      queue.Send(message);
    }
  }

Now I'm not passing a MessageQueue object to my SendMessage method. Instead, I'm sending an object that implements the IMessageQueue interface. My interface looks like this:

public interface IMessageQueue
  {
    void Send(object message);
  }

Now I can inject any object implementing the IMessageQueue interface into my test. For example, my real MessageQueue object already implemented the IMessageQueue interface looked like this:

 public class RealMessageQueue : IMessageQueue
  {
    var queue = MessageQueue.Create("AnyQueue");

    public void Send(object message)
    {
        queue.Send(message);
    }
  }

But another, a fake MessageQueue object could implement the interface also. I could add a property to my fake that supported testing:

public class FakeMessageQueue : IMessageQueue
  {
    public bool messageWasSent = false;
    public void Send(object message)
    {
      messageWasSent = true;
    }
  }

Now, with my FakeMessageQueue, I can actually create tests that return a value when the message is sent:

[TestMethod]
  public void Send_StringMessage_MessageWasSent()
  {
    var fakeMessageQueue = new FakeMessageQueue();

    var server = new Server();
    server.SendMessage(fakeMessageQueue, "message");

    Assert.IsTrue(fakeMessageQueue.messageWasSent);
  }

And that's the whole idea behind mocking -- the ability to change behavior of the objects you're working with to improve the quality of your tests.

But creating mock objects by coding every one of them by hand is a very tiring way to go. Today, there are tools to do the same thing, with much less hassle: isolation frameworks. This is one of the great benefits of tools like Typemock Isolator .NET -- the ability to fake any dependency, even privately declared variables and static/Shared methods or properties. If you want to use TDD, you're also going to need an isolation framework. There are several out there but, of course, I think TypeMock Isolator .NET is the best.

If you want more from Gil, he presents, blogs, and talks constantly about unit testing to encourage developers (from beginning to experienced) to implement unit testing as a core practice in their projects.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • VS Code 1.125 Adds Copilot Spend Meter After Billing Shock

    VS Code 1.125 adds in-editor visibility into additional Copilot budget usage as GitHub's AI-credit billing model continues to draw developer scrutiny.

  • TypeScript 7.0 RC Moves Microsoft's Go Rewrite Into the Mainline Compiler

    Microsoft's Go-based TypeScript rewrite has reached Release Candidate status, moving from a separate native-preview package into the regular TypeScript npm package while leaving some ecosystem-facing API work for TypeScript 7.1 or later.

  • Microsoft Highlights Visual Studio Live! Event Lineup and Longtime Developer Community Role

    A Microsoft MVP Blog post on Visual Studio Live!'s longevity arrives as the 2026 conference series continues with upcoming stops at Microsoft HQ, San Diego and Orlando.

  • Using Local AI to Cut Copilot Usage-Based Billing Shock

    After being gobsmacked by the new billing plan using almost all my monthly credits in one or two days, I tried pushing some Copilot-style coding work onto local models in VS Code. What I found was less "free AI" and more "pick your pain": cloud charges on one side, heavy local resource use and long waits on the other.

Subscribe on YouTube