Submitted by reesd on 2012/05/24 11:12
As a developer I can't stand not having unit tests. With IQ this actually becomes more important since think often silently fail and I personally can't get the debugger working. So I have been using a simple test approach with asserts to test my functions.
 
The idea is pretty simple. Whenever I write a function (e.g. MyFunc) I also write a test for it (e.g. MyFunc_Test). You can then run test function using the "Execute A Function" button.
 
I have the test function call my asserts. Here is the assert code I am using. If you are using a debugger that will give you a stacktrace you can uncomment the Err.Raise to go right to the problem. I often copy all my VBScript to a Excel VB Module to test it there for that reason.
 

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''' Testing Code

Sub AssertNull(expr)
    If Not IsNull(expr) Then
        Fail "AssertNull failed with " & expr
    End If
End Sub


Sub AssertEqual(lhs, rhs)
    If TypeName(lhs) <> TypeName(rhs) Then
        Fail "AssertEqual failed with unmatched TypeNames lhs " & TypeName(lhs) & " rhs " & TypeName(rhs)
    End If

    If Not (lhs = rhs) Then
        Fail "AssertEqual failed with lhs " & lhs & " rhs " & rhs
    End If
End Sub

Sub Assert(expr)
    If Not (expr) Then
        Fail "Assert failed with expr value " & expr
    End If
End Sub


Sub Fail(msg)
    'LogToFile msg
    MsgBox msg
    ' Uncomment when you have a debugger (or are testing in Excel VBA)
    'Err.Raise 8, "", msg
End Sub

' log what type something is
Function LogType(x, msg)
  Dim info
  info = msg & ": " & CStr(TypeName(x))
  if IsNull(x) then
    info = info & ", Null"
  else
    info = info & ", " & CStr(x)
  end if
 
  'MsgBox info
  LogToFile info
  LogType = x
end function

Comments

Thanks for this, Dave. Nice, clean and systematic way to work.
 
--------------------------------------------------------------------------------
Windows XP Home Edition, Service pack 3
Dell Vostro 1500, Ram:3gb, CPU: Intel Core2Duo T7500 2.2ghz