What is Automated Unit Testing?

Automated unit testing is the process of testing software using test scripts.
A unit test is a piece of code that executes another piece of code and compare the actual result with expected result.
In one of the previous chapters, you saw how to write a small class to calculate the Factorial of a number. Now let us try to write a small test script to test the Factorial() method. A simple test script will look like this:

public void TestFactorialMethod()
{
	// Instantiate the calculator class.
	Calculator calc = new Calculator();
	// Call the Factorial method to calculate the factorial of 5.
	int result = calc.Factorial(5);
	// We know that the factorial of 5 is 120. The job of the test method is
	// to compare the result from the factorial method with the expected value
	// and make sure it is same as the expected value/
	if ( result != 120 )
	{
		MessageBox.Show("Expected value is 120, but actual value is '" + result + "'.");
	}
}

The above method calls the Factorial method and compares the result. If the result is same as the expected result, then you know that the test is success. This indicates your Factorial method is working as expected.
In the above case, the test script calls the Factorial method with one input (5). In real development environment, you have to write several test scripts to test each method, with various input values and make sure the result is correct.
The above test script is not perfect. It displays a messagebox when the test fails. This requires someone has to manually look for the messageboxes.
Automated Unit Test Frameworks like NUnit solves this problem.

Tagged . Bookmark the permalink.

Leave a Reply