Search This Blog

Monday, March 27, 2006

Unit testing CAB applications

Recently I have investigated and started using the Microsoft Composite Appliction Block. Found it interesting in the first place. However, there are quite a few things missing from it. First and foremost the help with the CAB is not good enough. Not to miss, there has been some commitment from the GotDotNet project portal. Still a lot needs to be done. It took me a while to figure out how to Unit test these modules. More about simple things like using MDI Workspaces, Window Workspaces etc. It really tough if these things are not documented.

I thought of posting a bit of code to develop Unit testable work item. Let us call this UnitTestWorkItem. The following class can act as a root work item to which you can add other work items, views, services etc.


public class UnitTestWorkItem : WorkItem
{
public UnitTestWorkItem()
{
InitializeRootWorkItem(CreateBuilder());

Services.AddNew();
Services.AddNew();
}

public Builder Builder
{
get { return InnerBuilder; }
}

public IReadWriteLocator Locator
{
get { return InnerLocator; }
}


private Builder CreateBuilder()
{
Builder builder = new Builder();

builder.Strategies.AddNew(BuilderStage.Initialization);
builder.Strategies.AddNew(BuilderStage.Initialization);
builder.Strategies.AddNew(BuilderStage.Initialization);
builder.Strategies.AddNew(BuilderStage.Initialization);
builder.Strategies.AddNew(BuilderStage.Initialization);
builder.Strategies.AddNew(BuilderStage.PostInitialization);

builder.Policies.SetDefault(new ObjectBuiltNotificationPolicy());
builder.Policies.SetDefault(new SingletonPolicy(true));

return builder;
}
}



The above code will create the necesasry infrastructure to create the foundation to unit test your CAB applications. Here is a peice of sample code that instatiate a WorkItem and then gets it ready to test.

private CreateBankTellerView target;
private UnitTestWorkItem rootWorkItem;
private TellerWorkItem WiTeller;

rootWorkItem = new UnitTestWorkItem ();
WiTeller= rootWorkItem.WorkItems.AddNew();
WiTeller.Services.AddNew();
target = WiCust.SmartParts.AddNew();

The above code create the views, services and work items that need testing. However, to pass values to it and invoke some events you need to do a lot more. But here is the trick, I have used the VS.NET 2005 testing project that generate the accessor class for you. And that makes it easy to test the views.

CreateBankTellerViewAccessor accessor = new CreateBankTellerView(target);
accessor.txtFirstName = "John";

accessor.btnSave_Click(null,null);

In the above code line is firing the button click event. This is a good starting point to unit test CAB apps.

See you untill my next post. You can find similar code from the GotDotNet project portal. The code above has been adapted from the same site.

Thursday, March 09, 2006

Breaking through the inactivity

After two months of inactive blogging, here I am back. Uni study and work kept me away.