Testing with the Help of Test Helpers

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Deleting Matched Files | TOC | Logging Deleted Files 👉

When you wrote the integration tests for the list functionality, you used the testdata directory and a set of files to support your test cases. This procedure works well when the directory structure doesn’t change. But if you want to test file deletion, this may not be the best option because the files will be deleted after the first test, and you would have to keep creating them for every test run.

Instead, automate the creation and cleanup of the test directory and files for every test. In Go, you accomplish this by writing a test helper function and calling this function from within each test. A test helper function is similar to other functions, but you explicitly mark it as a test helper by calling the method t.Helper from the package testing. For example, when printing line and file information, if the helper function fails with t.Fatal, Go prints the line in the test function that called the helper function, instead of within the helper function. This helps with troubleshooting test errors, particularly if the helper function is called many times by different tests.

It’s also important to clean up after your tests. Cleaning up prevents wasting system resources and ensures that previous tests artifacts don’t impact future tests. To clean up after these tests, your test helper function…

--

--

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.