Go的测试方法

单元测试

测试文件需要以xxx_test.go的方式命名。

go test默认会执行当前目录下的所有测试文件。对于执行某个特定测试文件下的特定测试函数,参见-file和-run参数。

测试文件模板:

package gotest

import (
    "testing"
)

func Test_Division_1(t *testing.T) {
    if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function
        t.Error("除法函数测试没通过") // 如果不是如预期的那么就报错
    } else {
        t.Log("第一个测试通过了") //记录一些你期望记录的信息
    }
}

func Test_Division_2(t *testing.T) {
    t.Error("就是不通过")
}

测试函数是func TestXxx(t *testing.T) {}格式。

记录信息:t.Log("one test passed.", e)

产生错误信息:t.Error("Division did not work as expected.")

压力测试

函数格式是func BenchmarkXXX(b *testing.B) {}

  • go test不会默认执行压力测试的函数,如果要执行压力测试需要带上参数-test.bench,语法:-test.bench="test_name_regex",例如go test -test.bench=".*"表示测试全部的压力测试函数
  • 在压力测试用例中,请记得在循环体内使用testing.B.N,以使测试可以正常的运行
  • 文件名也必须以_test.go结尾

例子:

package gotest

import (
    "testing"
)

func Benchmark_Division(b *testing.B) {
    for i := 0; i < b.N; i++ { //use b.N for looping 
        Division(4, 5)
    }
}

func Benchmark_TimeConsumingFunction(b *testing.B) {
    b.StopTimer() //调用该函数停止压力测试的时间计数

    //做一些初始化的工作,例如读取文件数据,数据库连接之类的,
    //这样这些时间不影响我们测试函数本身的性能

    b.StartTimer() //重新开始时间
    for i := 0; i < b.N; i++ {
        Division(4, 5)
    }
}

执行go test -file webbench_test.go -test.bench=".*"以查看结果。

一些参数

  • go test -v

    显示详细信息。

  • go test -run=”regexp”

    运行正则表达式匹配的测试函数。

  • go test -file xxx_test.go

    指定当前目录下的测试文件,而不是全部测试。

  • go test -test.bench=”regexp”

    指定压力测试函数,由正则表达式匹配。所有函数可以写”.*”。

以下是所有的参数及解释(来源):

-bench regexp
    Run benchmarks matching the regular expression.
    By default, no benchmarks run. To run all benchmarks,
    use '-bench .' or '-bench=.'.

-benchmem
    Print memory allocation statistics for benchmarks.

-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).

-blockprofile block.out
    Write a goroutine blocking profile to the specified file
    when all tests are complete.

-blockprofilerate n
    Control the detail provided in goroutine blocking profiles by
    calling runtime.SetBlockProfileRate with n.
    See 'godoc 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.

-cover
    Enable coverage analysis.

-covermode set,count,atomic
    Set the mode for coverage analysis for the package[s]
    being tested. The default is "set".
    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 pkg1,pkg2,pkg3
    Apply coverage analysis in each test to the given list of packages.
    The default is for each test to analyze only the package being tested.
    Packages are specified as import paths.
    Sets -cover.

-coverprofile cover.out
    Write a coverage profile to the specified file after all tests
    have passed.
    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.

-cpuprofile cpu.out
    Write a CPU profile to the specified file before exiting.

-memprofile mem.out
    Write a memory profile to the specified file after all tests
    have passed.

-memprofilerate n
    Enable more precise (and expensive) memory profiles by setting
    runtime.MemProfileRate.  See 'godoc runtime MemProfileRate'.
    To profile all memory allocations, use -test.memprofilerate=1
    and set the environment variable GOGC=off to disable the
    garbage collector, provided the test can run in the available
    memory without garbage collection.

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

-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.

-run regexp
    Run only those tests and examples matching the regular
    expression.

-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 t
    If a test runs longer than t, panic.

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

发表评论

电子邮件地址不会被公开。