Today I needed to unit test a method that checked for and required a specific attribute on the class. I ended up with a fairly simple solution, the decorator pattern. Simply create a decorator for the type that needs the attribute, put the attribute on the decorator. Pass you mocked class to a new instance of the decorator when you pass to the method being tested. I sounds like more work then it is, of course it may not always make sense to go this route. Anyway, here’s the code.



using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace MockingClassesWithRequiredAttributes
{
[TestFixture]
public class Class1
{
[Test]
public void Test()
{
MockRepository mocks = new MockRepository();
IRun mockedRun = mocks.DynamicMock<IRun>();
using (mocks.Record())
{
mockedRun.Run();
LastCall.On(mockedRun);
}
using (mocks.Playback())
{
IRequireCategoryAttribute(new MockDecorator(mockedRun));
}
}

static void IRequireCategoryAttribute(IRun run)
{
object[] attributes = run.GetType().GetCustomAttributes(
typeof(System.ComponentModel.CategoryAttribute), false);
Assert.That(attributes.Length, Is.GreaterThan(0));
run.Run();
}
}

[System.ComponentModel.Category]
class MockDecorator : IRun
{
private readonly IRun run;

public MockDecorator(IRun run)
{
run = run;
}

public void Run()
{
_run.Run();
}
}

public interface IRun
{
void Run();
}
}

One downside to this approach is the MockDecorator class that is just for testing. Any other approaches you’ve used?