I dove into the
time standard library the other week to fix an outstanding bug. Turns out the bug is not quite a bug, but it might be… lets just say its status is complicated. Anyway, while diving through the code I found a new (to me) method for doing repetitive tests. Lets setup a fictitious function to test so I can show you why it’s so awesome.
Lets say the function input is a list of integers. Given this list, return the integer closest to
1 which is not in the list. So that is to say given the list of
[1,2,3,5], our function should return
4. Also of note, duplicates may exist, order is not guaranteed, and an empty list should return
1. Got it? Awesome, so here is our function signature:
We know the function’s signature, so lets do a little TDD. Here is how I would usually start:
go test and see that it fails. Fix the function implementation by making it return
1 and continue adding more test cases:
As you can imagine, this could drag out for a while depending on the complexity of the function. So how can we improve this repetitive testing process?
Enter test tables
Here’s where it gets awesome. I found this method of testing in the src/pkg/time/time_test.go file. Basically what you do is setup a data structure with your input and expected result. This could be a map or better yet, a slice of structs. Let’s convert the above test cases into a test table:
How awesome is that!? This has turned into one of my favorite testing methods in Go. It’s concise, readable, and so easy to extend. If we ever find a new edge case or want to expand our testing, we can just add a new case to our