12/02/2007

Silverlight Poor Man's Unit Test

Everyone knows Unit Tests are good, and Visual Studio 2008 excells in that, but unfortunately the built in testing projects will not accept Silverlight Assemblies as references. There are some creative ideas circling, from sharing your Silverlight files between SL and non-SL projects to compiling frameworks (e.g. NUnitLite) in SL.

I did neither. I wrote my own SL unit test framework. It looses to standard unit test frameworks on all counts save one. It has just one method of 5 lines of code:


private void Assert(bool condition)
{
TextBlock tb = new TextBlock();
tb.SetValue(Canvas.TopProperty, 30 * this.Children.Count);
tb.Foreground = new SolidColorBrush((condition) ? Color.FromRgb(30, 255, 30) : Color.FromRgb(255, 0, 0));
tb.Text = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name;
this.Children.Add(tb);
}


Here is how to use.
Create a Silveright project. Don't touch XAML, it was generated with the root canvas and that is enough. Past the above Assert function inot the genrated cs file. Add any number of test methods, all void and parameterless. Each test method ends with the call to Assert with some condition. True conditions will result in the method name printed in green on the canvas. Erroenous methods will be printed red. That is all to it.

No comments: