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

Barbara Streisand
Release: 2024-10-30 12:32:27
Original
181 people have browsed it

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>
    Copy after login
  2. Run the integration tests from within the main() test:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!