Unit Testing

Testing, no matter how its done, is time consuming. Automatic verification takes a long time to set up and can only work, at the moment, on small programs. Normal testing takes a long time to perform. The matter is made worse when bugs are fixed as they will inevitably introduce new problems. As a result, to be safe, we should run all of the tests again. How on earth can this be manageable in a large scale project. With the current tools we have looked at the answer is simply it is not. As such we could just do the best we can and hope for the best. Or we can employ a system called unit testing.

Unit testing is a way of running test scripts automatically. It is based around the idea of black box functionality testing. Consider a function to work out factorials.

Function factiorial (x As Integer);

I could write another function called testFactorial –

Function testFactorial() throws Exception {

factorial(10); // normal data

factorial(-99); // abnormal data

factorial(0); // Extreme data

factorial(4294967296); // Extreme data

}

The testFactorial function has a strange command after it called throws Exception. What this does is pass on any exception found without stopping the code there. Obviously the exception will still cause a problem later.

In order to run this test unit, along with other test units, a test suite is used. The test suite will run all unit tests, look to see if they throw an exception. If they throw an exception, that is have a fault, then that test is flagged up. If it does not then the test passes. These unit tests can then be fully automated to run every time you make changes to the code base. As such it can help identify bugs quicker and also reduce the amount of time taken up by testing.

You can use the unit test structure to do a lot of automated tests and it is common for most developers to create unit tests before they have even written the code. This is the secret to developing good code. If you know exactly how each function is supposed to work then there is no reason why you can not write your tests up front and have them tested while you are working on something else. It gives immediate feedback and also allows you to monitor changes to the code.

If you are interested in unit testing then look up JUnit for java. It will show you some of the power behind unit testing.