Writing Tests for colStats

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Developing the Initial Version of colStats | TOC | Benchmarking Your Tool 👉

You’re going to make a lot of changes to this code base to improve its performance. Before doing that, let’s write tests to make sure the program works correctly. Then you can use those tests to ensure the program still works as you change the underlying code.

For these tests, you’ll follow the same approach used to define tests in Writing Tests for the Markdown Preview Tool. You’ll create unit tests for the avg and sum statistics functions as well as for the csv2float function. For the integration tests, you’ll test the function run. You’ll also apply table-driven testing as you did for Testing with Table-Driven Testing.

Let’s start by writing unit tests for the statistics operations. In the same directory as the csv.go file, create the tests file csv_test.go. Open it in your text editor and add the package section:

performance/colStats/csv_test.go

​ ​package​ main

Add the import section. For these tests, you’ll use the bytes package to create buffers to capture the output, the errors package to validate errors, the io package to use the io.Reader interface, the testing package which is required to execute tests, and the iotest package to assist in executing tests that fail to read data.

--

--

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.