Thursday, December 03, 2009

TDD for the DSL Parser…

Here I will document the TDD aspects of the parser diagramed in a previous post.

I will also use this as a brief guide on how to do TDD in a real application environment.

I will be using xUnit as the testing framework, and Gallio as the test runner. (also for sake of simplicity I am using C# since for some reason F# xUnit tests are not showing up properly in Gallio at the moment.)

The empty test C# file is as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;

/// Blog DSR Parser unit tests
namespace blogParserTests
{
    public class ParserTests
    {

        // Setup or Teardown tests in constructor or destructor

        public ParserTests()
        { }

        ~ParserTests()
        { }


        // Tests Start here

        // Test batch for Token Class

        // Test batch for ScanBuffer Class

        // Test batch for Scanner Class

        // Test batch for Parser Class


    }
    
}

I am ordering the tests in bottom call stack order, so that all low level classes are tested prior to higher level ones. This is merely my preference for when I look at test results in Gallio or the GUI of xUnit.

Next up its time to put in a few tests, I normally only put in essential tests for the results of method calls and events when writing unit tests. The only time I test other things is if I need to test performance of some code or if I have some business login/formulas that need to be confirmed as working as defined by a client.

Client driven unit tests is normally done when I have a story to implement that does not have a UI but does have a function in a UI or some important back-end system (hidden from the user) processing. This is one of the cleanest ways to get the processing accepted for a story in an Scrum sprint.

OK back to the tests.

When I write tests I always do it in a simple format. An example test is shown below.

/// Create a simple token from a sample ScanBuffer
[Fact]
public void CreateSimpleToken()
{
    // Orchestrate Block

    // Activity Block

    // Assertion Block

    /// Make test fail to start with
    Assert.True(false);
}

When I code a single unit test I split it into 3 blocks of code or steps.

  • Orchestrate – This is where is setup any variables/objects/data that is needed to perform the specific testing I am doing.
  • Activity – This is where I do something that returns data or modifies Orchestrated data as part of the test
  • Assertion – This is where I test assertions against data returned or modified in the activity block of the test.

Also when I first create a test, I set it to always fail by default as you can see in the example.

In xUnit you define a test by using the [Fact] attribute.

In Gallio the test looks and fails as shown in the screen shot below.

Gallio - DSRParser Test

No comments: