Capturing Code Coverage from a Go Binary
Question:
How can code coverage metrics be captured when running integration tests against a Go binary?
Answer:
While the native Go coverage tool only works with unit tests, it is still possible to gather coverage data for integration tests.
Solution:
To achieve this:
Create a test file that executes the main() function:
<code class="go">func TestMainApp(t *testing.T) { go main() // Start integration tests }</code>
Run the integration tests from within the main() test:
<code class="go">cmd := exec.Command("./mybin", "somefile1") cmd.Run()</code>
Gather coverage statistics:
<code class="go">coverProfile := "coverage.out" test.RunMain() if err := testing.StartCoverage(coverProfile); err != nil { log.Fatalf("Coverage: %v", err) } defer testing.StopCoverage(coverProfile)</code>
Generate the coverage report:
<code class="go">if err := testing.RunTests(); err != nil { log.Fatalf("Coverage: %v", err) } cmd := exec.Command("go", "tool", "cover", "-html=coverage.out") cmd.Run()</code>
Additional Reference:
The above is the detailed content of How to Get Code Coverage from Integration Tests for Go Binaries?. For more information, please follow other related articles on the PHP Chinese website!