How to measure code coverage in Go?
Hello, colleagues! I've just started learning Go, and I'm having a problem with measuring code coverage. I'm writing a small REST API using net/http, and I want to make sure my tests cover all the main scenarios.
Here's an example of my code:
```go
package main
import (
"net/http"
"testing"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func TestHandler(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handler(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("expected 200, got %d", rr.Code)
}
}
```
I run tests via `go test`, but how do I find out what percentage of code is covered by tests? The documentation mentions the `-cover` flag, but I don't understand how to use it.
No answers yet.
Log in to leave an answer