Fake Objects

August 11, 20082 min

I was writing some tests today around some legacy code (its about 2 weeks old and not written with TDD) and wanted to make sure that some method was called when the parent method was invoked.  Unfortunately, I was having some problems with getting RhinoMocks working.  Since I was getting frustrated with some “stupid” tool and not making any progress, I decided to go back to first principles to look for a simpler way to write my test.

This was the code I was working with and I wanted to write a test that proved line 28 was called:

22  public virtual void AcceptMessage(IBusMessage message)
23  {
24      if (!Power)
25      {
26          return;
27      }
28      ProcessMessage(message);
29  }

If you look at the rest of the code, this method comes from an abstract base class and the method in question (line 28) is abstract, protected AND void, so just calling it and looking at the return value is not a strategy I can use.  To write the other tests I had written earlier in the day I had used the Fake Object concept just so I can get the object in the testing harness.  Keep in mind, I am not trying to fake any collaborator, just test the base class since it does real things I want to make sure happen (or get updated) as the design evolves (you might be thinking this is a dumb place to start with a test, but you have to start somewhere).

Since I have complete control over my fake object and the method I want to make sure is abstract, I can insert a sensing variable in my fake object and set its state when the method (ProcessMethod) is called, like so:

10  public bool MessageProcessed = false;
12  protected override void ProcessMessage(IBusMessage message)
13  {
14      MessageProcessed = true;
15  }

Here is my test:

63  [TestMethod]
64  public void AcceptMessageWithPowerTest()
65  {
66      // setup
67      FakeDevice test = new FakeDevice();
68      test.Power = true;
70      IBusMessage message = new BusMessage();
72      // exercise
73      test.AcceptMessage(message);
75      // verify
76      Assert.IsTrue(test.MessageProcessed, "Process message not called.");
78      // clean-up
79  }

OK, kinda like using a sledgehammer to hit a carpet nail, but it got me unstuck and back to a green bar.  Now, maybe I can spend sometime with RhinoMocks and figure out the easier way to do this.