Monday, February 28, 2011

Unit Testing Language Features

I was cleaning up some code I was working on and found a variable that was only used to hold the results of a function that returned a list for enumeration. I could make the code a little more readable by moving the function call directly into the loop. My only question was whether the function would be called each iteration.

We use NUnit at work for test-driven development and automated regression tests. If it works for testing scenarios in the code that we write, why not for language features also? Here is the test I came up with.
<Test(), Explicit()> Public Sub ForEachTest()
  Dim numRuns As Integer = 0

  For Each s As String In TestForEach(numRuns)
    Debug.Print(s)
  Next

  Assert.AreEqual(1, numRuns)
End Sub

Private Function TestForEach(ByRef numberOfRuns As Integer) As IList(Of String)
  numberOfRuns += 1

  Dim result As New List(Of String)
  result.Add("Test 1")
  result.Add("Test 2")
  result.Add("Test 3")

  Return result
End Function
If the iterator calls the function multiple times then the test would fail. I marked the test to be Explicit() so that it would not run with our automated build in the case I accidentally checked it in.

No comments:

Post a Comment