Golang unit testing is a long way | Go theme month

As a Gopher, in addition to writing business logic code, I also need to write a lot of unit tests, which accounts for a large part of the workload, enough to show its importance.

Project structure

Our project structure should be similar to the following, and there calc.gowill be a calc_test.gocorresponding test case file:

example/
   |--calc.go
   |--calc_test.go
复制代码

Let's take a look at the contents of the calc.gofile :

package example

func Add(a, b int) int {
    return a + b
}
复制代码

calc_test.goThe corresponding test case can look like this:

package example

import "testing"

func TestAdd(t *testing.T) {
    if ans := Add(1, 2); ans != 3 {
        t.Errorf("1 + 2 expected be 3, but %d got", ans)
    }

    if ans := Add(-1, -2); ans != -3 {
        t.Errorf("-1 + -2 expected be -3, but %d got", ans)
    }
}
复制代码

We can run go testand all test cases under this package will be executed.

go testCommand introduction

Here we use the go testcommand , which will automatically read *_test.gothe file named in the source directory, generate and run the executable file for testing.

The performance test system can give the performance data of the code to help the tester analyze the performance problem.

go testParameter Description:

  • -bench regexp Execute corresponding benchmarks, for example: -bench=.
  • -cover can view coverage
  • -run regexp only runs the function matched by regexp, for example: -run Array then executes the function containing the beginning of Array, this parameter supports wildcards *, and some regular expressions, for example ^,$
  • -v show test details

For example, execute all test cases in a file, and use to -vdisplay detailed information

$ go test helloworld_test.go
ok          command-line-arguments        0.003s
$ go test -v helloworld_test.go
=== RUN   TestHelloWorld
--- PASS: TestHelloWorld (0.00s)
        helloworld_test.go:8: hello world
PASS
ok          command-line-arguments        0.004s
复制代码

Summarize

This article briefly introduces how to write Golang unit tests and go testthe basic usage of , but Golang's unit tests are far from the same, so you must keep learning!

Guess you like

Origin juejin.im/post/6945103902429675533