Catalogue
VS Code's Go Generate Unit Test Was Super Handy ♪

VS Code's Go Generate Unit Test Was Super Handy ♪

🌐 日本語で読む

When writing tests in Go, I found that VS Code’s Go extension has a feature that easily generates the format for unit tests, and it turned out to be incredibly handy.

Let’s say you have a main.go file like the following.

1
2
3
4
5
6
7
8
package main

func hello(s string) string {
if s == "" {
return "world"
}
return s
}

Click on the function name to place your cursor there, then open the command palette (Command + Shift + p on Mac).

Type Go: Generate Unit Tests For Function and press Enter, and

the following main_test.go gets generated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import "testing"

func Test_hello(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := hello(tt.args.s); got != tt.want {
t.Errorf("hello() = %v, want %v", got, tt.want)
}
})
}
}

The fact that the function name becomes snake_case (Test_hello) is a bit bothersome, but this seems to happen when the function under test starts with a lowercase letter.

The format manages the information needed for test cases in a struct and iterates over them with a for loop.

TABLE DRIBEN TESTS

The arguments of func hello(string) are specified in args.

1
2
3
type args struct {
s string
}

If the test target were func(string, int), it would change to the following.

1
2
3
4
type args struct {
s string
i int
}

Write the test like the following,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import "testing"

func TestHello(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want string
}{
{
name: "return 'hello' if you set 'hello'",
args: args{
"hello",
},
want: "hello",
},
{
name: "空文字を指定したら world が返ってくる",
args: args{
"",
},
want: "world",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := hello(tt.args.s); got != tt.want {
t.Errorf("hello() = %v, want %v", got, tt.want)
}
})
}
}

When you run the tests, you can check whether each named test PASSes.

Half-width spaces are converted to _.

1
2
3
4
5
6
7
8
9
10
11
$ go test -count 1 -v .

$ go test -count 1 -v ./hoge
=== RUN TestHello
=== RUN TestHello/return_'hello'_if_you_set_'hello'
=== RUN TestHello/空文字を指定したら_world_が返ってくる
--- PASS: TestHello (0.00s)
--- PASS: TestHello/return_'hello'_if_you_set_'hello' (0.00s)
--- PASS: TestHello/空文字を指定したら_world_が返ってくる (0.00s)
PASS
ok github.com/kenzo0107/hoge 0.212s

Handy ♪

By the way, there are other Go: Generate options as well.

I hope this helps when writing Go tests in VS Code.
That’s all.

VS Code's Go Generate Unit Test Was Super Handy ♪

https://kenzo0107.github.io/en/2020/03/07/vscode-go/

Author

Kenzo Tanaka

Posted on

2020-03-07

Licensed under