Search⌘ K

Writing Tests for the Markdown Preview Tool

Explore writing effective tests for a Markdown preview tool in Go by creating unit tests for functions and integration tests for the run function. Learn to use golden files and io.Reader/io.Writer interfaces to validate complex outputs and manage test data within the project using Go's testing best practices.

When we tested the to-do tool previously, we wrote something similar to an integration test by compiling the tool and running it in the test cases. This was necessary as all the code was part of the main() function, which can’t be tested. For this application, we’ll take a different approach: we’ll write individual unit tests for each function, and use an integration test to test the run() function. We can do this now because the run() function returns values that can be used in tests.

This means we’re intentionally not testing some of the code that’s still in the main() function, such as the block that parses the command-line flags. We don’t have to write tests for that code because we can assume it’s already been tested by the Go team. When using external libraries and packages, trust that they’ve been tested by the developers who provided them. If we don’t trust the developers, we don’t use the library.

This also means we don’t need to write unit tests for the saveHTML() function since it’s essentially a wrapper ...