Really Simple Faking

Posted by Chris on September 04, 2006

Interaction based testing is a technique that is often made much more difficult and/or magical than it needs to be. Any experienced TDDer will have lots of arguments for and against using a mock framework for doing interaction based testing. Personally I have been very much for and very much against (using home-made fakes instead) at different times. However, I am very much against using them at all times. Sometimes what you want to test is just really really simple. For instance, here is a simple method that I want to test:

public void SetupInput()
input = inputFactory.Create();

The variable @inputFactory@ is a field holding a reference to a factory object passed in with the constructor, an example of dependency injection (another technique often made sound much more difficult than it really is). All I want my test to verify is that my class calls the Create method of the factory it is holding. I have other tests, probbably integration tests, that verify that it then uses this input correctly.

Here is the simplest way I can think of to test this:

private class FakeInputFactory : InputFactory
public string MethodsCalled = “”;

public Input Create()
MethodsCalled += “Create;”;

return null;

public void CreatesInputUsingFactory()
FakeInputFactory factory = new FakeInputFactory();
ClassUnderTest cut = new ClassUnderTest(factory);


Assert.AreEqual(“Create;”, factory.MethodsCalled);

With this simple and stupid (ok, it knows how to record stuff) fake I have verified that my class under test actually calls Create in inputFactory. I think this test is as readable as any so it serves it’s purpose well. Sometimes I use a mocking framework, sometimes I do simple stuff as this. All tools in the tool box are good to have.


Trackbacks are closed.

blog comments powered by Disqus