Step 5: Test, Test, Test, and Test Again
Wait, what? It's only one function. Surely we don't need to test it that much, do we? Yes, we do! You're unlikely ever to get to lavish time on this code snippet again. You've just rewritten it from scratch. One test run isn't enough. Do what you probably don't often have time to do: Write test harnesses.
Test harnesses are the backbone of a technique called test-driven development. David Astels provides an excellent explanation of this technique in his InformIT article "Test-Driven Development: Programming by Intention." I'll do my best to summarize it for our purposes: In essence, you want to test every possible input and output of the code in question. Test input that should make it break, input that should work, anything that might produce different behavior, and test for each discrete type of expected output. Listing 3 adds some tests to the previous code.
Listing 3Tests added to the code from Listing 2.
// this should work as long as the user has rights bool TestNullUserName() { try { MapDrive(local_drive, remote_drive, null, password); } catch (System.Exception) { return false; } return true; } // this should throw an exception bool TestNullRemoteDrive() { try { MapDrive(local_drive, null, user_name, password); } catch (System.Exception) { return true; } return false; } // this should not throw an exception bool TestKnownGoodParams() { try { MapDrive(local_drive, remote_drive, user_name, password); } catch (System.Exception) { return true; } return false; } ... and so on.
You can go out and download a unit-testing framework to help with something like this, but the magic of splitting our snippets apart is that test harnessing is possible (regardless of whether NUnit or its many permutations supports your desired language), whether or not you use a specialized framework. The tests in Listing 3 are examples of the types of behavior for which I normally testworking well with known good (or known acceptable) parameters, and checking for thrown exceptions where you expect them. Normally I would add another five or six functions for code like this example. You probably can see already what they might be.
Pretty nice. Certainly a far cry from what we had with the already very acceptable Visual Basic codenet profit for not much work. Now run this, work with the code until all the tests come up positive, and then you're ready for the next step.