blogger counters

Wednesday, October 04, 2006

Unit Tests for Learning and Experiments

Very often when I'm learning a new set of APIs, I like to write some test code to try things out. In the past I would create a new Windows Forms project and put some buttons into the form. Then I'd put my test code into the Click event handler for the buttons and use the debugger to step through the code and look at the results.

Not anymore! Now that I've gotten used to using Test-Driven Development to write code, I now write the small learnings as unit tests, or as a unit tests that call some test code in my application. Since unit tests are run without starting up the entire application, they run very quickly.

I put this into practice just today working on some code that uses the XmlSerializer to serialize some of my objects. In this case my unit test is very simple:

public void ShouldSerialize()
    MapNode first = new MapNode("first");
    MapNode second = new MapNode("second");
    MapNode child = new MapNode("child");
    MapNode[] nodes = new MapNode[] { first, second };
    FolderViewpointItem item = new FolderViewpointItem(10, nodes);

    XmlSerializer xml = new XmlSerializer(item.GetType());
    StringWriter writer = new StringWriter();
    xml.Serialize(writer, item);
Since I simply wanted to see the XML generated, I used the Assert.Fail method to display the XML as the message shown in Visual Studio's output window. Very fast, very simple. And I can use any of the classes in my application to try things out.


At 11/4/06, 6:01 PM, Anonymous Anonymous said...

I do the same (WinForm with test code in Button) thx for sharing this tip; please keep sharing your learnings its very useful.

At 4/4/07, 1:52 AM, Anonymous Anonymous said...

The other nice thing that you can do with this approach is to put all all your experimental test fixtures into a common project say experiments.csproj. With each class being a different kind of experiment. This way you greatly reduce the # of projects and you can always come back a year later and find that code you are looking for.


Post a Comment

<< Home