Home

Programming

Biography

Gallery

Music Links

Games

Mail Me

visual basic logo

Visual Basic Programming - Automating Testing

I've mentioned before that you should try to automate testing wherever possible.  There are two main reasons for this

  • You will fix most potential bugs when you are thinking of the necessary test cases
  • You can easily retest your code - thus you are more likely to regression test everything after you make changes in the future.

How do I set up testing

You need to follow the same steps for testing classes as for procedural code.  I will use procedures here for an example.

You have a function called calculate discount that is supposed to take the value of an item and calculate the level of discount applicable.

Quantity Discount
0 - 99 5%
100-499 10%
500+ 20%

 

The function could be set up as

Public Function CalcDiscount (Quantity As Long) As Double

The Test Cases

Quantity Expected Result
-1 Error
0 0.05
99 0.05
100 0.10
499 0.10
500 0.20
501 0.20
NULL Error
A Error
0.5 0.05

I have made a couple of assumptions - such as we are expecting an error for incorrectly formatted data.  By preparing the test cases I can check with others that my assumptions hold true to their original intention of the discount rule.

Automatic testing

Once we have our test cases planned we can run them.  The easiest way to do this is to place them in a text file so that they can be easily added to in  the future.  We simply read in each case and log the results to a test file for observation..

Public Function CalcDiscount(Quantity As Long) As Double
    If Quantity < 0 Then Err.Raise 0

    CalcDiscount = 0.05 'This is wrong but hey...
End Function

Public Function test()
'Function to test if the CalcDiscount function is correct
Dim lFileIn As Long
Dim lFileOut As Long
Dim vParam1 As Variant
Dim vResult As Variant
Dim vExpectedResult As Variant

    lFileIn = FreeFile
    Open "I:\test.dat" For Input As lFileIn
    lFileOut = FreeFile
    Open "I:\Result.dat" For Output As lFileOut

    While Not EOF(lFileIn)
        Input #lFileIn, vParam1, vExpectedResult
        On Error Resume Next 'Implictly clears the error object
        vResult = CalcDiscount(CLng(vParam1))
        If Err.Number <> 0 Then vResult = "Error"
        Print #lFileOut, vExpectedResult, vResult, (vExpectedResult = vResult)
    Wend

    Close lFileIn
    Close lFileOut

End Function

Download a copy of the test case file

Come back next week for more details on how to automatically test all of your functions each night and create a report for you to view in the morning.

Last updated insert_Date