One of the projects I’m working on these days is a Windows Forms application which is built using the Composite Application Block, which is something I’ve never used before. Recently I had to work out a way to write some tests that essentially verify that certain commands are executed. For simplicity, let’s assume the method I want to test looks like this:
public void CreateNewTemplate()
{
WorkItem.Commands[CommandNames.NewTemplate].Execute();
}
Most things in a CAB application seems to revolve around the WorkItem concept, and like you can see the method I want to test has a strong dependency on this. To verify that the command was executed then, I would need to somehow get control of the work item, ideally inserting my own mock of it. Turns out that’s not quite possible, cause there’s no interface defined for work items, and just newing up a WorkItem won’t do much good, as it requires some setup in order to function properly. Luckilly, a bit of Googling helped me out as out someone else had already figured this out and created a TestableRootWorkItem class.
The next hurdle was how to figure out if the command got executed. I couldn’t find any way to programatically attach a new listener to the command through the Work Item that actually worked (there are some promisingly named events in there, but I’ll be damned if I know when they’re supposed to be raised), so what I ended up having to do was to actually use CAB’s built in command routing mechanism by adding a CommandHandler method to the test fixture class itself, and registering the fixture with the work item (notice the rootWorkItem.Items.Add(this) call) so it would be hooked up:
[TestFixture]
public class When_creating_new_template
{
private bool _newTemplateCommandExecuted;
[SetUp]
public void Setup()
{
var rootWorkItem = new TestableRootWorkItem();
rootWorkItem.Items.Add(this);
var presenter = rootWorkItem.Items.AddNew<TemplatesPresenter>();
presenter.CreateNewTemplate();
}
[CommandHandler(CommandNames.NewTemplate)]
public void NewTemplateCommandHandler(object sender, EventArgs e)
{
_newTemplateCommandExecuted = true;
}
[Test]
public void NewTemplate_command_is_executed()
{
Assert.That(_newTemplateCommandExecuted, Is.True);
}
}
I’m quite pleased with how consise the test turned out in the end, but it took a bit of fiddling around to get there… CAB might be a step up from plain old WinForms coding, but it certainly has its quirks and dark alleys.