Wednesday, October 27, 2010

Creating a Unit Test in C#

Unit testing allows a developer to isolate different functions or parts of an application and show that those parts are working correctly. There are many benefits to creating unit tests, but two of the most important ones to me are finding bugs early in the development cycle and increasing the refactor-ability of the application with ability to run tests at any time. I'll now walk through a simple project with a unit test.


First, create a project called UnitTesting using the Class Library project template. Next, add a class named UnitTest to the project and add the following code snippet to that class so that it appears as follows...


namespace
UnitTesting
{
public static class UnitTest
{
public static bool IsMsSqlSmallDateTime(this DateTime input)
{
//January 1, 1900, through June 6, 2079
return (input >= new DateTime(1900, 1, 1) && input <= new DateTime(2079, 6, 6));
}
}
}

Next, right-click on the function name and select "Create Unit Tests...". A new project is added to the solution with a class named UnitTestTest.cs. Running the test now will result in an Inconclusive result, therefore let's look at the test code in more detail. Change the test method to the following code and then rerun the test...

[TestMethod()]
public void IsMsSqlSmallDateTimeTestTooOld()
{
DateTime input = new DateTime();
input = Convert.ToDateTime("01/01/1899");

bool expected = false;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

This method sets the input to a date we know to be older than a valid SQL date and calls our function. We are expecting a false return then we assert that our assumption and the function return the predicted results. You could also create the following tests to check for date that is too new and one that is just right...

[TestMethod()]
public void IsMsSqlSmallDateTimeTestTooYoung()
{
DateTime input = new DateTime();
input = Convert.ToDateTime("01/01/2080");

bool expected = false;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

[TestMethod()]
public void IsMsSqlSmallDateTimeTestJustRight()
{
DateTime input = new DateTime();
input = System.DateTime.Now;

bool expected = true;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

This has been a brief intro to unit test, I hope this helps out.

No comments:

Post a Comment