Thursday, September 25, 2014

Designing Your Application to be Unit Testable

The easiest way to structure any application so that it is unit testable is to break up the main sections of the work being down into some basic pieces.  These are:

  1. Get your data
  2. Do work with your data
  3. Commit changes to your data
With this basic application structure you can now separate the pulling and processing of the data.  You are in complete control of that data being used by the processing code and can manipulated it as you see fit.  It is the ideal structure for unit testable code.  

public class MyMainWorker
{
    public void RunWorker()
    {
        // Optional begin your transaction here
        DataSet ds = GetData();
        object o = Execute(ds);
        // Begin your transaction
        SaveData(ds);
        // Commit your transaction
    }

    private void SaveData(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private object Execute(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private DataSet GetData()
    {
        throw new NotImplementedException();
    }
}

1 comment: