golang 单元测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rznice/article/details/82285917
  运行 go test 命令将执行当前目录下的包的测试代码,它会寻找 *_test.go 文件,并在这些文件中,寻找符合 TestXxx(*testing.T){} 签名的函数(即,接收 *testing.T 参数的函数,命名为 TestXxx,Xxx 可以是任何不以小写字符开头的名字)。这个测试代码不会影响正常的编译过程,只在执行 go test 时被使用。
  首先通过go test -help查看go test的帮助文件:
go test -help
usage: go test [build/test flags] [packages] [build/test flags & test binary flags]

In addition to the build flags, the flags handled by 'go test' itself are:

    -args
        Pass the remainder of the command line (everything after -args)
        to the test binary, uninterpreted and unchanged.
        Because this flag consumes the remainder of the command line,
        the package list (if present) must appear before this flag.

    -c
        Compile the test binary to pkg.test but do not run it
        (where pkg is the last element of the package's import path).
        The file name can be changed with the -o flag.

    -exec xprog
        Run the test binary using xprog. The behavior is the same as
        in 'go run'. See 'go help run' for details.

    -i
        Install packages that are dependencies of the test.
        Do not run the test.

    -json
        Convert test output to JSON suitable for automated processing.
        See 'go doc test2json' for the encoding details.

    -o file
        Compile the test binary to the named file.
        The test still runs (unless -c or -i is specified).

The test binary also accepts flags that control execution of the test; these
flags are also accessible by 'go test'.

    -bench regexp
        Run only those benchmarks matching a regular expression.
        By default, no benchmarks are run.
        To run all benchmarks, use '-bench .' or '-bench=.'.
        The regular expression is split by unbracketed slash (/)
        characters into a sequence of regular expressions, and each
        part of a benchmark's identifier must match the corresponding
        element in the sequence, if any. Possible parents of matches
        are run with b.N=1 to identify sub-benchmarks. For example,
        given -bench=X/Y, top-level benchmarks matching X are run
        with b.N=1 to find any sub-benchmarks matching Y, which are
        then run in full.

    -benchtime t
        Run enough iterations of each benchmark to take t, specified
        as a time.Duration (for example, -benchtime 1h30s).
        The default is 1 second (1s).

    -count n
        Run each test and benchmark n times (default 1).
        If -cpu is set, run n times for each GOMAXPROCS value.
        Examples are always run once.

    -cover
        Enable coverage analysis.
        Note that because coverage works by annotating the source
        code before compilation, compilation and test failures with
        coverage enabled may report line numbers that don't correspond
        to the original sources.

    -covermode set,count,atomic
        Set the mode for coverage analysis for the package[s]
        being tested. The default is "set" unless -race is enabled,
        in which case it is "atomic".
        The values:
        set: bool: does this statement run?
        count: int: how many times does this statement run?
        atomic: int: count, but correct in multithreaded tests;
            significantly more expensive.
        Sets -cover.

    -coverpkg pattern1,pattern2,pattern3
        Apply coverage analysis in each test to packages matching the patterns.
        The default is for each test to analyze only the package being tested.
        See 'go help packages' for a description of package patterns.
        Sets -cover.

    -cpu 1,2,4
        Specify a list of GOMAXPROCS values for which the tests or
        benchmarks should be executed. The default is the current value
        of GOMAXPROCS.

    -failfast
        Do not start new tests after the first test failure.

    -list regexp
        List tests, benchmarks, or examples matching the regular expression.
        No tests, benchmarks or examples will be run. This will only
        list top-level tests. No subtest or subbenchmarks will be shown.

    -parallel n
        Allow parallel execution of test functions that call t.Parallel.
        The value of this flag is the maximum number of tests to run
        simultaneously; by default, it is set to the value of GOMAXPROCS.
        Note that -parallel only applies within a single test binary.
        The 'go test' command may run tests for different packages
        in parallel as well, according to the setting of the -p flag
        (see 'go help build').

    -run regexp
        Run only those tests and examples matching the regular expression.
        For tests, the regular expression is split by unbracketed slash (/)
        characters into a sequence of regular expressions, and each part
        of a test's identifier must match the corresponding element in
        the sequence, if any. Note that possible parents of matches are
        run too, so that -run=X/Y matches and runs and reports the result
        of all tests matching X, even those without sub-tests matching Y,
        because it must run them to look for those sub-tests.

    -short
        Tell long-running tests to shorten their run time.
        It is off by default but set during all.bash so that installing
        the Go tree can run a sanity check but not spend time running
        exhaustive tests.

    -timeout d
        If a test binary runs longer than duration d, panic.
        If d is 0, the timeout is disabled.
        The default is 10 minutes (10m).

    -v
        Verbose output: log all tests as they are run. Also print all
        text from Log and Logf calls even if the test succeeds.

    -vet list
        Configure the invocation of "go vet" during "go test"
        to use the comma-separated list of vet checks.
        If list is empty, "go test" runs "go vet" with a curated list of
        checks believed to be always worth addressing.
        If list is "off", "go test" does not run "go vet" at all.

The following flags are also recognized by 'go test' and can be used to
profile the tests during execution:

    -benchmem
        Print memory allocation statistics for benchmarks.

    -blockprofile block.out
        Write a goroutine blocking profile to the specified file
        when all tests are complete.
        Writes test binary as -c would.

    -blockprofilerate n
        Control the detail provided in goroutine blocking profiles by
        calling runtime.SetBlockProfileRate with n.
        See 'go doc runtime.SetBlockProfileRate'.
        The profiler aims to sample, on average, one blocking event every
        n nanoseconds the program spends blocked. By default,
        if -test.blockprofile is set without this flag, all blocking events
        are recorded, equivalent to -test.blockprofilerate=1.

    -coverprofile cover.out
        Write a coverage profile to the file after all tests have passed.
        Sets -cover.

    -cpuprofile cpu.out
        Write a CPU profile to the specified file before exiting.
        Writes test binary as -c would.

    -memprofile mem.out
        Write an allocation profile to the file after all tests have passed.
        Writes test binary as -c would.

    -memprofilerate n
        Enable more precise (and expensive) memory allocation profiles by
        setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
        To profile all memory allocations, use -test.memprofilerate=1.

    -mutexprofile mutex.out
        Write a mutex contention profile to the specified file
        when all tests are complete.
        Writes test binary as -c would.

    -mutexprofilefraction n
        Sample 1 in n stack traces of goroutines holding a
        contended mutex.

    -outputdir directory
        Place output files from profiling in the specified directory,
        by default the directory in which "go test" is running.

    -trace trace.out
        Write an execution trace to the specified file before exiting.

Each of these flags is also recognized with an optional 'test.' prefix,
as in -test.v. When invoking the generated test binary (the result of
'go test -c') directly, however, the prefix is mandatory.

The 'go test' command rewrites or removes recognized flags,
as appropriate, both before and after the optional package list,
before invoking the test binary.

For instance, the command

    go test -v -myflag testdata -cpuprofile=prof.out -x

will compile the test binary and then run it as

    pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out

(The -x flag is removed because it applies only to the go command's
execution, not to the test itself.)

The test flags that generate profiles (other than for coverage) also
leave the test binary in pkg.test for use when analyzing the profiles.

When 'go test' runs a test binary, it does so from within the
corresponding package's source code directory. Depending on the test,
it may be necessary to do the same when invoking a generated test
binary directly.

The command-line package list, if present, must appear before any
flag not known to the go test command. Continuing the example above,
the package list would have to appear before -myflag, but could appear
on either side of -v.

When 'go test' runs in package list mode, 'go test' caches successful
package test results to avoid unnecessary repeated running of tests. To
disable test caching, use any test flag or argument other than the
cacheable flags. The idiomatic way to disable test caching explicitly
is to use -count=1.

To keep an argument for a test binary from being interpreted as a
known flag or a package name, use -args (see 'go help test') which
passes the remainder of the command line through to the test binary
uninterpreted and unaltered.

For instance, the command

    go test -v -args -x -v

will compile the test binary and then run it as

    pkg.test -test.v -x -v

Similarly,

    go test -args math

will compile the test binary and then run it as

    pkg.test math

In the first example, the -x and the second -v are passed through to the
test binary unchanged and with no effect on the go command itself.
In the second example, the argument math is passed through to the test
binary, instead of being interpreted as the package list.
import (
    "fmt"
    "testing"
)

func TestAss(t *testing.T)  {
    fmt.Println("TestAss11")
}

func TestAsss(t *testing.T)  {
    fmt.Println("TestAsss11")
}

func TestAc(t *testing.T)  {

}
  运行  go test 
 go test
TestAss11
TestAsss11
PASS
ok      mlib    0.004s
  运行 go test -test.v 或者 go test -v ,参数v显示相关信息
go test -test.v 
=== RUN   TestOps
--- PASS: TestOps (0.00s)
=== RUN   TestAss
TestAss11
--- PASS: TestAss (0.00s)
=== RUN   TestAsss
TestAsss11
--- PASS: TestAsss (0.00s)
=== RUN   TestAc
--- PASS: TestAc (0.00s)
PASS
ok      mlib    0.004s
  可以通过-run或者-test.run指定要测试的方法,后跟正则表达式。
  go test -run="TestAsss" 或者 go test -run TestAsss
go test -run="TestAsss"
TestAsss11
PASS
ok      mlib    0.003s


go test -run="TestAss"
TestAss11
TestAsss11
PASS
ok      mlib    0.004s
  -count 执行的次数;
go test -count 3
TestAss11
TestAsss11
TestAss11
TestAsss11
TestAss11
TestAsss11
PASS
ok      mlib    0.004s
  跳过测试(Skipping tests)
  一些测试可能要求要有特定的上下文环境。例如,一些测试可能需要调用一个外部的命令,使用一个特殊的文件,或者需要一个可以被设置的环境变量。当条件无法满足时,(如果)不想让那些测试失败,可以简单地跳过那些测试:
import (
    "fmt"
    "testing"
)

func TestAss(t *testing.T)  {
    fmt.Println("TestAss11")
}

func TestAsss(t *testing.T)  {
    fmt.Println("TestAsss11")
}

func TestAc(t *testing.T)  {
    t.Skip("TestAc不满足条件")
}
  测试:
go test -v
=== RUN   TestOps
--- PASS: TestOps (0.00s)
=== RUN   TestAss
TestAss11
--- PASS: TestAss (0.00s)
=== RUN   TestAsss
TestAsss11
--- PASS: TestAsss (0.00s)
=== RUN   TestAc
--- SKIP: TestAc (0.00s)
    manager_test.go:54: TestAc不满足条件
PASS
ok      mlib    0.004s
  通常是用 -short 命令行标志来实现这个跳过的特性,如果标志被设置的话,反映到代码中,testing.Short() 将简单地返回 true(就像是 -v 标志一样,如果它被设置,通过判断 testing.Verbose() ,你可以打印出额外的调试日志)。
  当测试需要运行较长时间时,而你又很着急的话,你可以执行 go test -short,如果提供这个包的开发者又刚好实现了这个功能,运行时间长的测试将会被跳过。
import (
    "fmt"
    "testing"
)

func TestAss(t *testing.T)  {
    fmt.Println("TestAss11")
}

func TestAsss(t *testing.T)  {
    fmt.Println("TestAsss11")
}

func TestAc(t *testing.T)  {
    t.Skip("TestAc不满足条件")
}

func Test_Short(t *testing.T) {
    fmt.Println("Test_Short")
    if testing.Short() {
        t.Skip("Test_Short")
    }
}
  跳过只是一个可选项,-short 标志只是一个标示,具体还依赖于开发者,他们可以选择(这种标示生效时是否)运行的测试,来避免一些运行比较慢的断言被执行。
  这里还有 -timeout 标志,它能够被用来强制退出限定时间内没有运行完的测试。例如,运行这个命令 go test -timeout 1s 以执行下面的测试:
func Test_Timeout(t *testing.T) {
    //fmt.Println("Test_Timeout")
    time.Sleep(2 * time.Second)
}
  测试:
 go test -run Test_Timeout -timeout 1s
panic: test timed out after 1s

goroutine 17 [running]:
testing.(*M).startAlarm.func1()
..........
  并行执行测试(Parallelizing tests)
  默认情况下,指定包的测试是按照顺序执行的,但也可以通过在测试的函数内部使用 t.Parallel()来标志某些测试也可以被安全的并发执行。在并行执行的情况下,只有当那些被标记为并行的测试才会被并行执行,所以只有一个测试函数时是没意义的。它应该在测试函数体中第一个被调用(在任何需要跳过的条件之后),因为它会重置测试时间:
func TestAss(t *testing.T)  {
    fmt.Println("TestAss11")
}

func TestAsss(t *testing.T)  {
    fmt.Println("TestAsss11")
}

func TestAc(t *testing.T)  {
    t.Skip("TestAc不满足条件")
}


func Test_Short(t *testing.T) {
    fmt.Println("Test_Short")
    if testing.Short() {
        t.Skip("Test_Short")
    }
}

func Test_Timeout(t *testing.T) {
    //fmt.Println("Test_Timeout")
    time.Sleep(2 * time.Second)
}

func Test_Parallel(t *testing.T) {
    t.Parallel()
    fmt.Println("Test_Parallel")
}
  在并发情况下,同时运行的测试的数量默认取决于 GOMAXPROCS。它可以通过 -parallel n 被指定(go test -parallel 4)
  另外一个可以实现并行的方法,尽管不是函数级粒度,但却是包级粒度,就是类似这样执行 go test p1 p2 p3(也就是说,同时调用多个测试包)。在这种情况下,包会被先编译,并同时被执行。当然,这对于总的时间来说是有好处的,但它也可能会导致错误变得具有不可预测性,比如一些资源被多个包同时使用时(例如,一些测试需要访问数据库,并删除一些行,而这些行又刚好被其他的测试包使用的话)。
  为了保持可控性,-p 标志可以用来指定编译和测试的并发数。当仓库中有多个测试包,并且每个包在不同的子目录中,一个可以执行所有包的命令是 go test ./...,这包含当前目录和所有子目录。没有带 -p 标志执行时,总的运行时间应该接近于运行时间最长的包的时间(加上编译时间)。运行 go test -p 1 ./...,使编译和测试工具只能在一个包中执行时,总的时间应该接近于所有独立的包测试的时间加上编译的时间的总和。你可以自己试试,执行 go test -p 3 ./...,看一下对运行时间的影响。
  还有,另外一个可以并行化的地方(你应该测试一下)是在包的代码里面。多亏了 Go 非常棒的并行原语,实际上,除非 GOMAXPROCS 通过环境变量或者在代码中显式设置为 GOMAXPROCS=1,否则,包中一个goroutines 都没有用是不太常见的。想要使用 2 个 CPU,可以执行 GOMAXPROCS=2 go test,想要使用 4 个 CPU,可以执行 GOMAXPROCS=4 go test,但还有更好的方法:go test -cpu=1,2,4 将会执行 3 次,其中 GOMAXPROCS 值分别为 1,2,和 4。
  -cpu 标志,搭配数据竞争的探测标志 -race。竞争探测是一个很神奇的工具,在以高并发为主的开发中不得不使用这个工具(来防止死锁问题),你写自己的测试代码前,建议看一下标准库中的testing/iotest,testing/quick 和 net/http/httptest 软件包。

https://blog.csdn.net/qian_xiaoqian/article/details/54344856

猜你喜欢

转载自blog.csdn.net/rznice/article/details/82285917