Sunday, September 26, 2010

Test Driven Approach - Positive Impact for Developers - Workshop II

First of all, there were couple of useful tools for Test Driven within Visual Studio .NET 2008 or 2010.

These are the tools the I usually use: -
1. NUnit
2. TestDriven.NET
3. JetBrains ReSharper

Note: JetBrains resharper is not free though.

So, after all, how should we start the development based on the requirements?

I usually create a new Test Project first, named Calculator.Tests.

For any TDD development, we should always attempt to write the tests from highest level possible with the simplest code. To achieve this, we should always attempt with the simplest API that we are going to deal with.

So, I would imagine the calculator class to work like this: -
Calculator cal = new Calculator();
var result = cal.Evaluate(formula);
Hence, I created a class within the Calculator.Tests as such: -
using NUnit.Framework;

namespace Calculator.Tests
{
    [TestFixture]
    public class CalculatorTester
    {
        private Calculator _calculator;

        [SetUp]
        public void SetUp()
        {
            _calculator = new Calculator(); 
        }

        [TestCase("5 + 6", "11")]
        [TestCase("3 - 2", "1")]
        [TestCase("5 * 6", "30")]
        [TestCase("12 / 6", "2")]
        [TestCase("2 * 3 - 4 / 5 + 6", "11.2")]
        [TestCase("5 + 6%", "5.3")]
        [TestCase("reciproc(2)", "0.5")]
        [TestCase("pow(2,3)", "8")]
        [TestCase(new [] {"A + B + C", string.Empty},
                    "Incompatible data type evaluation test.",
                    typeof(IncompatibleDataTypeFormulaException))]
        public void EvaluationTest(string formula, string expected)
        {
            var result = _calculator.Evaluate(formula);
            Assert.AreEqual(result.ToString(), expected);
        }
    }
}
Now with have almost demonstrated most of the features needed using various test cases based on TestCaseAttribute of NUnit 2.5.

You may be asking, so, this is the business logic, where is the UI testing? Isn't it we must start from the UI?

Yes, you got it half spots on. We must start from the UI (highest level), however are you sure this calculator class is just a business logic class? We shall see then.

Now, lets try to fix all the compilation error by creating some fundamental skeleton for it to compile.
public class Calculator
{
    public double Evaluate(string formula)
    {
        throw new NotImplementedException();
    }
}

public class IncompatibleDataTypeFormulaException:Exception
{
}
Now that we have written the unit tests and the compilation is done. We should test run it and see all of them failed.



As expected, all test cases failed. I would be extremely surprised if any of this passed. :)

So, the next assignment is to get them green.

No comments:

Post a Comment