liveBook · Manning

Code coverage

As explained in Go in Practice, Second Edition

Code coverage is a measurement of which portions of program code are executed by a test suite.

Code coverage measures which portions of program code a test suite executes. Go reports coverage alongside test results, helping reveal functions or implementations that tests do not exercise. section 1.2.4 section 6.3.4

Use Go's built-in commands to inspect coverage at increasing levels of detail:

  • Run go test -cover to print the percentage of covered statements. section 1.2.4 section 6.3.4
  • Run go test -v -cover -coverprofile mycover.out to save formatted coverage data. section 6.3.4
  • Run go tool cover -html mycover.out to visualize covered and uncovered code in a browser. section 6.3.4

Uncovered functions

An application with foo, bar, and baz functions has tests for foo and bar only. Running the tests reports 66.7% statement coverage, making the untested portion visible for follow-up work. section 6.3.4

Figure 6.5 Our test coverage in the browser
figure

Open the browser visualization to inspect test coverage across the application in a single view. section 6.3.4

How Go in Practice, Second Edition covers it

How deep it goes
Calculates statement coverage and visualizes results, but does not prescribe a target such as 100 percent.
Examples
Uses foo, bar, and baz functions, tests two of them, and reports 66.7 percent coverage.
What it assumes
Assumes familiarity with Go tests and test execution while leaving test-selection strategy to the developer.
What you can do after
Diagnose/debug with it by locating code that existing tests do not exercise through command output or browser visualization.
How it connects
Connects unit testing, test suites, Go tooling, coverage profiles, browser visualization, and IDE test displays.

Also explained in

Compare how 14 books explain code coverage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.