DEV Community

Cover image for Go in VSCode: Showing code coverage after saving your code
Vuong
Vuong

Posted on • Edited on

Go in VSCode: Showing code coverage after saving your code

Requisites

Note: you don't need all packages in above wiki, but everything is good for your Golang development process on vscode, except gometalinter because it already archived on github

Configuration

Add some configs into User settings, like below:



{
    "go.coverOnSave": true,
    "go.coverageDecorator": {
        "type": "gutter",
        "coveredHighlightColor": "rgba(64,128,128,0.5)",
        "uncoveredHighlightColor": "rgba(128,64,64,0.25)",
        "coveredGutterStyle": "blockgreen",
        "uncoveredGutterStyle": "blockred"
    },
    "go.coverOnSingleTest": true
}


Enter fullscreen mode Exit fullscreen mode

Instead "gutter" on type, you can try with "highlight".

You can take a look on available options vscode-go supports for gutter style here https://github.com/microsoft/vscode-go/blob/master/src/goCover.ts#L39

Example

I'm having this file



// filename: services/person.go
package services

type Person struct {
    name string
}

func (person *Person) Name() string {
    return person.name
}

func (person *Person) Foo() string {
    return person.name
}




Enter fullscreen mode Exit fullscreen mode

Here is my testing code



// filename: services/person_test.go
package services

import (
    "testing"
)

func TestPeople_Name(t *testing.T) {
    tests := []struct {
        name   string
        person *Person
        want   string
    }{
        {"should return a name", &Person{"Vuong"}, "Vuong"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := tt.person.Name(); got != tt.want {
                t.Errorf("DecisionMaker.Name() = %v, want %v", got, tt.want)
            }
        })
    }
}




Enter fullscreen mode Exit fullscreen mode

Every time I've done to saving my code, the result of code coverage on services/person.go will be shown like the below one.

Alt Text

Happy coding!

Top comments (4)

Collapse
 
sajirdev profile image
sajir-dev

Image description

In vs-code cmnd + shift + p will open navigator
type Go: Toggle Test Coverage in current package for showing the coverage

Collapse
 
bernardolm profile image
Bernardo Loureiro

Hi vuong, good post!
Which font do you use on this print with coverage?
Regards!

Collapse
 
vuong profile image
Vuong

Hi Bernardo, it's Victor Mono!

Collapse
 
bernardolm profile image
Bernardo Loureiro

Great, Vuong! Really thank you!