I have a small little function in a VB6 codebase:
Public Function GetEquivalentCode(Optional ByVal code As String) As String
If IsMissing(code) Or code = vbNullString Then code = m_GlobalCode
Dim result As String
If StringStartsWith("ABC", code) Then
result = "ABC2013"
Else
result = code
End If
GetEquivalentCode = result
End Function
The implications of this function are massive, so before I deployed it I wrote a small test to ensure it returns the correct/expected value in all cases:
Public Sub GetEquivalentCodeTest()
Dim result As String
m_GlobalCode = "ABC2013"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "ABC2014"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "ABC2013A"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "XYZ2013"
result = GetEquivalentCode
Debug.Assert result = "XYZ2013"
m_GlobalCode = "SOMETHING ELSE"
result = GetEquivalentCode
Debug.Assert result = "SOMETHING ELSE"
m_GlobalCode = vbNullString
result = GetEquivalentCode
Debug.Assert result = vbNullString
Debug.Print "GetEquivalentCodeTest: Passed."
End Sub
Running this method from the immediate pane prints GetEquivalentCodeTest: Passed.
, and if I tweak it to make it fail, it breaks at the assertion that evaluates to False
.
Is this the best way to write automated tests in VB6?
Colleagues call me a "purist" - I take it as a compliment. The thing is, without this test method, the mere fact that you give "ABC2014" to the function and it returns "ABC2013" can (will) be a major WTF for anyone maintaining this code in 2 years' time (including myself); the way I see it, these tests document what the [funky] business rules are.
Is there a way to write the test so as to make the business rules even more obvious?