Home >Backend Development >Golang >## How to Achieve Complete Coverage in Functional Tests: Bridging the Gap Between Code and Execution?
How to Show Complete Coverage in Functional Tests
Problem:
Functional tests execute compiled binary code, leaving room for uncovered blind spots.
Code Snippet:
<code class="go">package main import ( "fmt" "math/rand" "os" "time" ) var exitCode int func Test_main(t *testing.T) { go main() exitCode = <-exitCh } func TestMain(m *testing.M) { m.Run() // can exit because cover profile is already written os.Exit(exitCode) } func main() { rand.Seed(time.Now().UTC().UnixNano()) for { i := rand.Int() fmt.Println(i) if i%3 == 0 { os.Exit(0) } if i%2 == 0 { os.Exit(1) } time.Sleep(time.Second) } }</code>
Solution:
1. Exclude Main Function Using Build Tags:
<code class="go">//+build !test package main func main() { os.Exit(doFunc()); }</code>
Build with tags:
go test -c -coverpkg=. -o example -tags test
2. Extract Functionality to Testable Code:
Avoid testing the main function by extracting functionality into other classes. Use func TestMain to control code execution on the main thread.
3. Use Mocking:
Create mocks for dependencies to isolate specific code paths and improve testability.
4. Timeouts for Coverage:
Add a timeout to the test to give the coverage tool time to write the profile before the application exits.
Example with Timeouts:
<code class="go">func exit(code int) { exitCh <- code time.Sleep(1 * time.Second) // Allow time for coverage data to be written os.Exit(code) }</code>
Benefits:
The above is the detailed content of ## How to Achieve Complete Coverage in Functional Tests: Bridging the Gap Between Code and Execution?. For more information, please follow other related articles on the PHP Chinese website!