8 Testing And Tooling

 

This chapter covers

  • Unit Testing With The testing Package
  • Test-Driven Development.
  • Code Coverage
  • Test Fixtures and Helpers
  • Benchmarking
  • Fuzzing

Testing sometimes gets a bad rap as a chore or an afterthought—​something to be added later, after the difficult work of solving problems is done. Often, you will hear programmers talk about testing in terms of "peace of mind", meaning that tests can help verify that your software continues to work as expected, even as new features are added or parts of the underlying logic are changed. If the tests keep passing, the reasoning goes, your code is still functioning as intended, or at least in all the ways that matter.

Peace of mind is certainly an important benefit of testing, but if all you are concerned with is verifying your code after the fact, then you’re missing out on a lot of what testing can do for you, especially in a language with a solid set of tooling like what is available in Go.

Rather than being defensive, tests can be proactive, and you can wield them like a scalpel instead of a shield, identifying and targeting areas for improvement in existing code.

The extended tooling around profiling and testing remains one of Go’s enduring strengths and, when combined with benchmarking, enables you to identify and target areas for performance improvement. By creating a benchmark and adding a couple of flags, you can get targeted stats on CPU usage and memory allocation, sometimes down to the individual line.

8.1 Test Files And Functions

8.2 Running Tests with go test

8.3 Test Functions

8.4 Test Lifecycle

8.4.1 Fatal And Non-Fatal Failures

8.5 Test Driven Design: A Calculator With A Twist

8.5.1 Black Box Testing

8.5.2 Writing Tests For Error Conditions

8.5.3 Writing Good Test Logs

8.5.4 Choosing Testing Targets

8.5.5 Table-Driven Testing

8.5.6 Implementation And Initial Testing

8.5.7 Code Coverage

8.6 Simulating Dependencies with an HTTP Server

8.7 Beyond Unit Tests

8.7.1 Benchmark Testing

8.7.2 Fuzz Testing

8.8 Summary