Testing with Table-Driven Testing

Powerful Command-Line Applications in Go — by Ricardo Gerardi (41 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Developing a File System Crawler | TOC | Deleting Matched Files 👉

When you’re writing tests for your command-line tool, you often want to write test cases that cover different variations of the function or tool usage. By doing this, you ensure that the different parts of your code are working, increasing the reliability of your tests and tool. For example, to test the filterOut function from the walk tool, it’s a good idea to define test cases for the different conditions such as filtering with or without extension, matching or not, and minimum size.

One of the benefits of Go is that you can use Go itself to write test cases. You don’t need a different language or external frameworks. By leveraging Go, you use all the language’s features to help define your test cases. A common pattern for writing test cases that cover different variations of the function you’re testing is known as table-driven testing. In this type of testing, you define your test cases as a slice of anonymous struct, containing the data required to run your tests and the expected results. You then iterate over this slice using loops to execute all test cases without repeating code. The Go testing package provides a convenient function Run that runs a subtest with the specified name. Let’s use this approach to test this version of the tool.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.