Skip to content

Unit Testing Example

AndrewM- edited this page Oct 6, 2015 · 6 revisions

Unit Testing in Rubberduck uses the Arrange Act Assert framework for testing. Arrange is where the environment the test runs in is created. For example, an object's properties are set or a small table with test data is created. Act is where the method, sub or function under test is run and the result of the test assigned to a variable. Assert is where the result of the test is marked. In the Assert statement the developer has entered the expected result of the test. The actual result, which is in the variable is then compared to the expected result and if they are the same, the test is passed.

More information on the Arrange Act Assert framework from Coding Craft

With unit testing in Rubberduck, only one test should be performed for each test procedure. The advantage of the Arrange Act Assert framework is that it forces a cleanly structured approach to testing where test set up code is separated from code that runs the test and code that evaluates the result. Clean test code helps identify when the test code, which doubles as feature specification in agile methodologies, is inaccurate or confused.

Example:

I use a function called Have() to determine if I have some data to work with. It returns false for nulls, empty strings and zeros. The code is below.

`

  Public Function Have(ByVal item As Variant) As Boolean

 'Returns True if the tested variable is not null, not zero and not an empty string
 'Simplifies handling nulls and empty strings in validation code.  Opposite of 'No()'

On Error GoTo procerr

If IsNull(item) Then
    Have = False
ElseIf Len(Trim(item)) = 0 Then  'Faster than Item <> ""
    Have = False
ElseIf item = 0 Then
    Have = False
Else
    Have = True
End If 

exitproc:
    Exit Function

procerr:
    'Errors sometimes occur if an unbound control is referenced
    Have = False

End Function

`

I put the following code into a Rubberduck test module to test if have() returns the correct response to a null.

`

  '@TestMethod
 Public Sub **TestHave_Null**()
    On Error GoTo TestFail

    'Arrange:
    Dim x As Variant
    x = Null

   'Act:
   x = Have(x)

   'Assert:
   Assert.IsFalse (x)

TestExit:
   Exit Sub
TestFail:
    Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub

`

Once this test has been created, open Test Explorer and refresh the test list so that new name for the test procedure (in bold above) is loaded into Test Explorer. Then run all tests. If the test succeeds, then it will get a green tick.