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 | package main |
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 | package main |
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.
The arguments of func hello(string) are specified in args.
1 | type args struct { |
If the test target were func(string, int), it would change to the following.
1 | type args struct { |
Write the test like the following,
1 | package main |
When you run the tests, you can check whether each named test PASSes.
Half-width spaces are converted to _.
1 | $ go test -count 1 -v . |
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 ♪