2 Idioms and testing

 

This chapter covers

  • Exploring idiomatic principles with packages.
  • Satisfying the standard library interfaces.
  • Writing and running tests using the tools provided by Go.
  • Using table-driven testing and subtests to improve maintainability.
  • Writing example tests to generate runnable documentation.

Automated tests ensure the code works today and will continue to work in the future. Focusing on testing right away builds a solid mindset for the remainder of the book. We'll cover the testing fundamentals, while the next chapters will explore it in greater depth.

We'll explore how to write and test a simple URL parser package called url. A simple replica of the standard library's url package with the same name. Although simple, it shows us how to properly name packages and their items, handle errors, and implement interfaces from the standard library. We'll then test the package once we have its basic version in place.

After learning the fundamentals of testing in Go, we'll explore table-driven tests to reduce duplication. While table-driven testing is helpful, it has some pitfalls, which we'll address using subtests. Lastly, we'll learn how to generate documentation using example tests.

The next chapter dives into measuring test coverage, benchmarking, and optimization.

2.1 Groundwork

2.1.1 Overview

2.1.2 Implementation

2.2 Idioms

2.2.1 Names

2.2.2 Errors

2.2.3 Fields

2.2.4 Standard interfaces

2.3 Testing

2.3.1 Writing tests

2.3.2 Running tests

2.3.3 Writing a failing test

2.3.4 Writing descriptive test failure messages

2.3.5 Fixing the code

2.4 Table-driven tests

2.4.1 Creating a table of test cases

2.4.2 Writing a table-driven test

2.4.3 Running a specific test

2.4.4 Issues with table-driven tests

2.5 Subtests

2.5.1 Understanding subtests

2.5.2 Writing a table-driven test with subtests

2.5.3 Running subtests

2.5.4 Fixing the code

2.6 Example tests

2.6.1 Writing an example test

2.6.2 Running example tests

2.7 Other testing tools

2.8 Summary