Tuesday, April 9, 2013

Consider Dichotomies When Writing Unit Tests

When writing unit tests, it's one thing to have code coverage (i.e. the paths through the code are being exercised by your unit tests), but it's another art to make sure that your tests are exercising the important properties of your function. One of these important properties is the dichotomies (i.e. classifications) of data that the function processes. For example, consider the following Scala function that simply returns a filtered list of strings where the first character is a digit.


  def getStringsStartingWithDigit(s: List[String]): List[String] = {
    s.filter(p => p.charAt(0).isDigit)
  }


In this example, the following dichotomies come to mind for unit tests:

  • An empty list
  • A list that contains strings beginning with a digit, as well as strings that do not begin with a digit
  • A list that doesn't contain any strings beginning with a digit
  • A list that where all strings begin with a digit

The following unit tests will cover these scenarios.


@RunWith(classOf[JUnitRunner])
class StringListTest extends FunSuite {
 test("filtering an empty list should return an empty list") {
   val expected = List()
   val actual = getStringsStartingWithDigit(List())
   assert(expected === actual)
 }
 
 test("filtering a list that contains strings starting with a digit") {
   val expected = List("1alpha", "2bravo")
   val actual = getStringsStartingWithDigit(List("1alpha", "2bravo", "echo"))
   assert(expected === actual)
 }

 test("filtering a list with no strings that start with a digit") {
   val expected = List()
   val actual = getStringsStartingWithDigit(List("alpha", "bravo", "echo"))
   assert(expected === actual)
 }

 test("filtering a list where all strings start with a digit") {
   val expected = List("1alpha", "2bravo", "3echo")
   val actual = getStringsStartingWithDigit(List("1alpha", "2bravo", "3echo"))
   assert(expected === actual)
 }
}

Dichotomies are just the classifications/groups of data that are interesting for the tests. Here are some examples of dichotomies that crop-up quite often during development, so keep them in mind when writing your unit tests:
  • Empty and Full Lists
  • Even and Odd Integers
  • Lists of Even and Odd Lengths
  • Positive and Negative Numbers

No comments:

Post a Comment