A base fixture class can help reduce repetitive code

This is one of those posts where you throw up some code and hope you’re doing it right (if I’m not, do tell).


As you start to write a large number of tests, you realize that there’s a lot of small repetition going on. Some of it is directly related to testing infrastructure (mocks and DI), while others are just utility functions. Nothing as complex as an ObjectMother mind you, but things that ought to be streamlined. For a while I’ve been using a base class which most of my fixtures inherit from. I stole a good-chunk size of it from someone (I’m thinking Chad Myers?). Figured it might be helpful to others if I posted it up:

namespace CodeBetter.Tests
{
using System;
using System.Collections.Specialized;
using System.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
using StructureMap;

[TestFixture]
public abstract class BaseFixture
{
[SetUp]
public void MainSetup()
{
Mocks = new MockRepository();
BeforeEachTest();
}
[TearDown]
protected void MainTeardown()
{
ObjectFactory.ResetDefaults();
AfterEachTest();
}
[TestFixtureSetUp]
public void FixtureSetup()
{
BeforeAllTests();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
AfterAllTests();
}

public MockRepository Mocks { get; private set; }

protected virtual void BeforeEachTest() { }
protected virtual void AfterEachTest() { }
protected virtual void BeforeAllTests() { }
protected virtual void AfterAllTests() { }

protected T Dynamic<T>()
{
var mock = Mocks.DynamicMock<T>();
if (typeof(T).IsInterface)
{
ObjectFactory.Inject(typeof(T), mock);
}
return mock;
}
protected T Strict<T>(params object[] parameters)
{
var mock = Mocks.StrictMock<T>(parameters);
if (typeof(T).IsInterface)
{
ObjectFactory.Inject(typeof(T), mock);
}
return mock;
}
protected T Partial<T>(params object[] parameters) where T : class
{
return Mocks.PartialMock<T>(parameters);
}
protected T Stub<T>(params object[] parameters)
{
var stub = Mocks.Stub<T>(parameters);
if (typeof(T).IsInterface)
{
ObjectFactory.Inject(typeof(T), stub);
}
return stub;
}
protected IDisposable Playback
{
get { return Mocks.Playback(); }
}
protected IDisposable Record
{
get { return Mocks.Record(); }
}
protected void ReplayAll()
{
Mocks.ReplayAll();
}
protected void Replay(object o)
{
Mocks.Replay(o);
}
protected void VerifyAll()
{
Mocks.VerifyAll();
}

protected NameValueCollection CreateParameters(params string[] values)
{
if (values == null)
{
return new NameValueCollection(0);
}
if (values.Length % 2 != 0)
{
throw new ArgumentException(“Expecting an even number of values”);
}
var nvc = new NameValueCollection(values.Length / 2);
for (int i = 0; i < values.Length; i += 2)
{
nvc.Add(values[i], values[i + 1]);
}
return nvc;
}
//recurse through the base type to find the field f you have to
protected void SetField(object o, string fieldName, object value)
{
FieldInfo field = null;
for (var type = o.GetType(); field == null && type.BaseType != null; type = type.BaseType)
{
field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
}
if (field == null)
{
throw new ArgumentException(“Couldn’t not find field with that name”);
}
field.SetValue(o, value);
}
}
}


There are really four purposes to this class. The first is simply to clean up the ugliness around the setup/teardown attribute by providing overrideable methods (BeforeEachTest, BeforeAllTests, AfterEachTest, AfterAllTests).


Next it makes creating and managing mocks a little easier. Instead of:

_mock = new MockRepository();
_store = mock.DynamicMock<IStore>();

You do:

_store = Dynamic<IStore>();

That might not seem all that useful, but paired with our third feature, it ends up being a time-saver. That third feature being: whenever you create a mock object as such, it automatically gets injected into our DI tool (in this case,StructureMaps…I noticed SM 2.5 has auto-mocking capabilities, so this might not be needed anymore?).


Finally, it provides some utility functions. I find myself having to pass hashtables around every now and again and find the CreateParameters to be a small time saver. Next is the SetField method which uses reflection to set a private field. This should probably be avoided if possible, but I do use it as needed; such as setting an Id on objects with only a public getter:

var user = new User();
SetField(user, “_id”, 3);

Happy Coding

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

One Response to A base fixture class can help reduce repetitive code

  1. Cool! I think I just grab this and add it to my VS2008 Testproject template. I had something similiar in there, but not as sophisticated. :)