Writing Tests Instead of Comments

Jon commented

Unit tests are the best comments you can leave a developer or your future self.

Well, these aren’t unit test exactly, but they are tests. The question is, do they adequately document the code?

First, the code

Public Property Get GetStartDate(ByVal dtTomorrow As Date) As Date

Dim clsTomorrow As CHoliday
Dim dtReturn As Date
Dim i As Long

Set clsTomorrow = Me.HolidayByHolidayDate(dtTomorrow)

If clsTomorrow Is Nothing Then
dtReturn = dtTomorrow
Else
For i = 1 To 7
If Me.IsWorkDay(dtTomorrow + 1) Then
dtReturn = dtTomorrow + 1
Exit For
End If
Next i
End If

GetStartDate = dtReturn

End Property

Public Property Get GetEndDate(ByVal dtStart As Date) As Date

Dim i As Long
Dim dtReturn As Date

If Weekday(dtStart, vbMonday) < 6 Then dtReturn = dtStart Else For i = 1 To 7 If Me.IsWorkDay(dtStart + i) Then dtReturn = dtStart + i Exit For End If Next i End If GetEndDate = dtReturn End Property

And, the tests.

Sub TEST_Main()

TEST_Initialize
TEST_HolidayNormal
TEST_HolidayFriday
TEST_HolidayTomorrow
TEST_HolidayMonday

Debug.Print "Passed"

End Sub

Sub TEST_Initialize()

Set gclsApp = New CApp
gclsApp.Initialize

End Sub

Sub TEST_HolidayNormal()

Dim dtDate As Date
Dim dtStart As Date

dtDate = #8/29/2013# 'typical weekday
dtStart = gclsApp.Holidays.GetStartDate(dtDate + 1)
Debug.Assert dtStart = #8/30/2013# 'starts tomorrow
Debug.Assert gclsApp.Holidays.GetEndDate(dtStart) = #8/30/2013# 'end tomorrow

End Sub

Sub TEST_HolidayFriday()

Dim dtDate As Date
Dim dtStart As Date

dtDate = #8/23/2013# 'typical friday
dtStart = gclsApp.Holidays.GetStartDate(dtDate + 1)
Debug.Assert dtStart = #8/24/2013# 'sat
Debug.Assert gclsApp.Holidays.GetEndDate(dtStart) = #8/26/2013# 'mon

End Sub

Sub TEST_HolidayTomorrow()

Dim dtDate As Date
Dim dtStart As Date

dtDate = #11/27/2013# 'day before thanksgiving
dtStart = gclsApp.Holidays.GetStartDate(dtDate + 1)
Debug.Assert dtStart = #11/29/2013# 'starts on Friday
Debug.Assert gclsApp.Holidays.GetEndDate(dtStart) = #11/29/2013# 'ends on friday

End Sub

Sub TEST_HolidayMonday()

Dim dtDate As Date
Dim dtStart As Date

dtDate = #8/30/2013#
dtStart = gclsApp.Holidays.GetStartDate(dtDate + 1)
Debug.Assert dtStart = #8/31/2013# 'starts saturday
Debug.Assert gclsApp.Holidays.GetEndDate(dtStart) = #9/3/2013# 'ends tuesday

End Sub

Posted in VBA

2 thoughts on “Writing Tests Instead of Comments

  1. The tests pretty accurately describe what the code is trying to accomplish (offset long weekends properly). And if your future self needs to change or extend that you make sure you didn’t break it. What more would you you say in comments that isn’t said in the test code.

Leave a Reply

Your email address will not be published. Required fields are marked *