Creating and Running a Test HarnessAs discussed in the Functional Decomposition section of Chapter 3 Excel and VBA Development Best Practices, you should strive to break your application into as many single-purpose, reusable procedures as possible. After you've done this, however, you need to verify that these procedures work under all circumstances. Testing them manually within your application is tedious, time-consuming and not very thorough.The proper way to test a procedure is to write a wrapper procedure that calls the procedure to be tested in a loop, passing it all possible combinations of arguments and verifying the results to ensure that they are correct. This wrapper procedure is called a test harness and we show you how to build one in this section. The workbook containing the procedures we're about to demonstrate is called TestHarnessDemo.xls and is located on the CD in the \Concepts\Ch16VBA Debugging folder.One frequently useful single-purpose procedure takes a full path and filename string and breaks it into its path and filename components, optionally returning one or both to the calling procedure. The ReturnPathAndFilename procedure shown in Listing 16-6 does this.NOTEBecause of its use of the VBA InStrRev function, which was first introduced in Excel 2000, the ReturnPathAndFilename procedure will not work in Excel 97. Listing 16-6. The ReturnPathAndFilename ProcedureTo verify that this procedure works as expected we need to create a test harness that feeds it large numbers of full path and filename strings and then concatenates the returned split path and filename values and verifies that the specified file exists. If the split is performed incorrectly on any test string, we know there is a bug in the procedure that needs to be fixed. The test harness that performs this operation is shown in Listing 16-7. Listing 16-7. The Test Harness for the ReturnPathAndFilename ProcedureIn the TestHarness procedure we use the FileSearch object to create a large array of full path and filename strings. We loop this array and feed each of these strings to the ReturnPathAndFilename procedure. We then concatenate the path and filename returned by the procedure and verify that it refers to a valid file. If any full path and filename strings are split incorrectly, we print the results to the Immediate window and display an error message upon completion. Otherwise we display a success message.Using this technique, you can run thousands of full path and filename strings through the function and verify that it handles them correctly in a very short period of time. Verifying as many procedures as possible using the test harness approach should be considered a best programming practice. ![]() |