Integrate

The TestMathFunctions unit test in the preceding section is a bit of a cheat because it combines the tests for two procedures: Inverse and CubeRoot. In general, unit tests and procedures have a one-to-one correspondence to make it easier to locate problems when they occur. Also, unit tests are easier to use if they don’t display message boxes, because that requires you to manually click through the test.

For those reasons, I generally follow these conventions when writing unit tests:

  • Return a string indicating pass/fail from each test.

  • Where the results aren’t pass/fail, return the result of the operation.

  • Call the unit tests from a Test xxx Main procedure and display the results in the Immediate window using Debug.Print.

The following code shows unit tests for the QuickRead and QuickWrite procedures from Chapter 3 written with those conventions in mind:

Const fpathtest = "c:\temp.txt"   Sub TestFilesMain( ) Debug.Print TestQuickWrite Debug.Print TestQuickRead End Sub   Private Function TestQuickWrite( ) As String Dim s As String Dim result As String result = "failed" s = "This is some sample text." If Files.QuickWrite(s, fpathtest, True) Then result = "passed" TestQuickWrite = "TestQuickWrite " & result End Function   Private Function TestQuickRead( ) As String Dim s1 As String, s2 As String Dim result As String result = "failed" s1 = "This is some sample text." s2 = Files.QuickRead(fpathtest) If s1 = s2 Then result = "passed" TestQuickRead = "TestQuickRead " & ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.