Home  >  Article  >  Backend Development  >  How to Get Code Coverage from Integration Tests for Go Binaries?

How to Get Code Coverage from Integration Tests for Go Binaries?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 12:32:27165browse

How to Get Code Coverage from Integration Tests for Go Binaries?

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:

  1. Create a test file that executes the main() function:

    <code class="go">func TestMainApp(t *testing.T) {
        go main()
        // Start integration tests
    }</code>
  2. Run the integration tests from within the main() test:

    <code class="go">cmd := exec.Command("./mybin", "somefile1")
    cmd.Run()</code>
  3. 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>
  4. 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:

  • [Go coverage with external tests](https://blog.golang.org/cover-external-tests)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn