Monday, October 5, 2009

Visual Studio First Unit Test

Well, I decided to go with the built in unit test that Visual Studio 2008 provides simply because of the integration and everyone has it available without any installs.  The whole point is to just working with unit tests.  The lessons learned can be applied to any unit test software like NUnit.  So I started out with a simple method that does the same thing Math.Pow() does, raises a decimal to a power, returning a decimal.  (MyMath.cs)
public static class MyMath
{
  public static decimal MyPower(decimal num, int power)
  {
    int i = 0;
    decimal retval = 1;

    while (i < power)
    {
      retval *= num;
      i++;
    }

    return retval;
  }
}
After creating the method, i select the Test menu in Visual Studio and New Test....  In the Add New Test dialog box, I select the Unit Test template and name it TestPower.cs, and select "Create a new Visual C# test project...".  I click OK and name the new project TestProjectSimpleUnitTest and click Create.

I am presented with a new project TestProjectSimpleUnitTest that contains TestPower.cs.  Scrolling to the end of that file, I see:
[TestMethod]
public void TestMethod1()
{
      //
      // TODO: Add test logic    here
      //
}
I rename that method to TestMyPower() and delete the comments.  I right click the TestProjectSimpleUnitTest project and set it as the Startup Project.  I then press F5 to start the unit test and see that it passed.

Now, lets actually test MyPower.  First thing we have to do is add a reference to the SimpleUnitTest project in the TestProjectSimpleUnitTest project.  Add a using clause at the top of the TestPower.cs file:
using SimpleUnitTest;
and fill in my test method like this:
[TestMethod]
public void TestMethodMyPower()
{
  Assert.AreEqual(9m, MyMath.MyPower(3, 2), "3 to power of 2");
  Assert.AreEqual(1m, MyMath.MyPower(3, 0), "3 to power of 0");
  Assert.AreEqual(27m, MyMath.MyPower(3, 3), "3 to power of 3");
}
All my tests pass in this case.  But, supposing they didn't it's easy to set a breakpoint in the MyPower code or in the unit test code and select debug in the Test Results pane and debug your code in a controlled fashion that does not impact your project using MyPower!

Next time I'm going to get into the real good stuff... creating unit test for a database driven application!

No comments:

Post a Comment