Testing with the Help of Test Helpers

Learn how to create the test case to test our application.

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

Instead, we automate the creation and cleanup of the test directory and files for every test. In Go, we 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 we 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.

Get hands-on with 1200+ tech skills courses.