golang自家的单元测试做的很好了,自需要"文件名_test.go" 就可以在里面写单元测试,而且go test命令也很强大,可以只运行单个测试函数,在goland 可以点击单元测试函数前面的图标,但是切换到vscode就需要自己动手了。go test 主要参考https://godoc.org/testing
单元测试写起来也比较容易,设定号 输入 判断 输出 与预想是否一致,一致则ok,否则 则报错。
单元测试是一门学问,考虑的问题也很多,比如很多边界问题、如何自动化、测试样本等等很多东西
go test -run ''      # Run all tests.
go test -run Foo # Run top-level tests matching "Foo", such as "TestFooBar". 测试所有包含Foo的函数,想测试某个函数 就把名字写全
go test -run Foo/A= # For top-level tests matching "Foo", run subtests matching "A=".
go test -run /A=1 # For all top-level tests, run subtests matching "A=1".

  

package testing

import "testing"

Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the “go test” command, which automates execution of any function of the form

func TestXxx(*testing.T)

where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine.

Within these functions, use the Error, Fail or related methods to signal failure.

To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the “go test” command is run. For more detail, run “go help test” and “go help testflag”.

Tests and benchmarks may be skipped if not applicable with a call to the Skip method of *T and *B:

func TestTimeConsuming(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
...
}

Benchmarks

Functions of the form

func BenchmarkXxx(*testing.B)

are considered benchmarks, and are executed by the "go test" command when its -bench flag is provided. Benchmarks are run sequentially.

For a description of the testing flags, see https://golang.org/cmd/go/#hdr-Description_of_testing_flags.

A sample benchmark function looks like this:

func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("hello")
}
}

The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output

BenchmarkHello    10000000    282 ns/op

means that the loop ran 10000000 times at a speed of 282 ns per loop.

If a benchmark needs some expensive setup before running, the timer may be reset:

func BenchmarkBigLen(b *testing.B) {
big := NewBig()
b.ResetTimer()
for i := 0; i < b.N; i++ {
big.Len()
}
}

If a benchmark needs to test performance in a parallel setting, it may use the RunParallel helper function; such benchmarks are intended to be used with the go test -cpu flag:

func BenchmarkTemplateParallel(b *testing.B) {
templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
b.RunParallel(func(pb *testing.PB) {
var buf bytes.Buffer
for pb.Next() {
buf.Reset()
templ.Execute(&buf, "World")
}
})
}

Examples

The package also runs and verifies example code. Example functions may include a concluding line comment that begins with "Output:" and is compared with the standard output of the function when the tests are run. (The comparison ignores leading and trailing space.) These are examples of an example:

func ExampleHello() {
fmt.Println("hello")
// Output: hello
} func ExampleSalutations() {
fmt.Println("hello, and")
fmt.Println("goodbye")
// Output:
// hello, and
// goodbye
}

The comment prefix "Unordered output:" is like "Output:", but matches any line order:

func ExamplePerm() {
for _, value := range Perm(4) {
fmt.Println(value)
}
// Unordered output: 4
// 2
// 1
// 3
// 0
}

Example functions without output comments are compiled but not executed.

The naming convention to declare examples for the package, a function F, a type T and method M on type T are:

func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }

Multiple example functions for a package/type/function/method may be provided by appending a distinct suffix to the name. The suffix must start with a lower-case letter.

func Example_suffix() { ... }
func ExampleF_suffix() { ... }
func ExampleT_suffix() { ... }
func ExampleT_M_suffix() { ... }

The entire test file is presented as the example when it contains a single example function, at least one other function, type, variable, or constant declaration, and no test or benchmark functions.

Subtests and Sub-benchmarks

The Run methods of T and B allow defining subtests and sub-benchmarks, without having to define separate functions for each. This enables uses like table-driven benchmarks and creating hierarchical tests. It also provides a way to share common setup and tear-down code:

func TestFoo(t *testing.T) {
// <setup code>
t.Run("A=1", func(t *testing.T) { ... })
t.Run("A=2", func(t *testing.T) { ... })
t.Run("B=1", func(t *testing.T) { ... })
// <tear-down code>
}

Each subtest and sub-benchmark has a unique name: the combination of the name of the top-level test and the sequence of names passed to Run, separated by slashes, with an optional trailing sequence number for disambiguation.

The argument to the -run and -bench command-line flags is an unanchored regular expression that matches the test's name. For tests with multiple slash-separated elements, such as subtests, the argument is itself slash-separated, with expressions matching each name element in turn. Because it is unanchored, an empty expression matches any string. For example, using "matching" to mean "whose name contains":

go test -run ''      # Run all tests.
go test -run Foo # Run top-level tests matching "Foo", such as "TestFooBar".
go test -run Foo/A= # For top-level tests matching "Foo", run subtests matching "A=".
go test -run /A=1 # For all top-level tests, run subtests matching "A=1".

Subtests can also be used to control parallelism. A parent test will only complete once all of its subtests complete. In this example, all tests are run in parallel with each other, and only with each other, regardless of other top-level tests that may be defined:

func TestGroupedParallel(t *testing.T) {
for _, tc := range tests {
tc := tc // capture range variable
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
...
})
}
}

Run does not return until parallel subtests have completed, providing a way to clean up after a group of parallel tests:

func TestTeardownParallel(t *testing.T) {
// This Run will not return until the parallel tests finish.
t.Run("group", func(t *testing.T) {
t.Run("Test1", parallelTest1)
t.Run("Test2", parallelTest2)
t.Run("Test3", parallelTest3)
})
// <tear-down code>
}

Main

It is sometimes necessary for a test program to do extra setup or teardown before or after testing. It is also sometimes necessary for a test to control which code runs on the main thread. To support these and other cases, if a test file contains a function:

func TestMain(m *testing.M)

then the generated test will call TestMain(m) instead of running the tests directly. TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run. It should then call os.Exit with the result of m.Run. When TestMain is called, flag.Parse has not been run. If TestMain depends on command-line flags, including those of the testing package, it should call flag.Parse explicitly.

A simple implementation of TestMain is:

func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
os.Exit(m.Run())
}

golang test 单元测试的更多相关文章

  1. Golang之单元测试

    文件名必须以_test.go结尾 使用go test 执行单元测试 例 package main func add(a, b int) int { return a + b } func sub(a, ...

  2. Golang Testing单元测试指南

    基础 可以通过 go test -h 查看帮助信息. 其基本形式是: go test [build/test flags] [packages] [build/test flags & tes ...

  3. golang 单元测试&&性能测试

    一:单元测试 1.为什么要做单元测试和性能测试 减少bug 快速定位bug 减少调试时间 提高代码质量 2.golang的单元测试 单元测试代码的go文件必须以_test.go结尾 单元测试的函数名必 ...

  4. golang单元测试简述

      Golang中内置了对单元测试的支持,不需要像Java一样引入第三方Jar才能进行测试,下面将分别介绍Golang所支持的几种测试: 一.测试类型   Golang中单元测试有功能测试.基准测试. ...

  5. golang精选100题带答案

    能力模型 级别 模型 初级 primary 熟悉基本语法,能够看懂代码的意图: 在他人指导下能够完成用户故事的开发,编写的代码符合CleanCode规范: 中级 intermediate 能够独立完成 ...

  6. Go面试题精编100题

    Golang精编100题 选择题 1.   [初级]下面属于关键字的是()A. funcB. defC. structD. class 参考答案:AC 2.   [初级]定义一个包内全局字符串变量,下 ...

  7. Go_笔试题记录-不熟悉的

    1.golang中没有隐藏的this指针,这句话的含义是() A. 方法施加的对象显式传递,没有被隐藏起来 B. golang沿袭了传统面向对象编程中的诸多概念,比如继承.虚函数和构造函数 C. go ...

  8. go语言常见面试题

    前言 从网上找了一些面试题,觉得有意思的我都记录下来,自己学习和大家一起学习吧. 有些初级的题目只放答案,一些值得探讨的问题我会写上我自己的分析过程,希望大家多多交流. 原文链接 选择题 1.[初级] ...

  9. go面试题-基础类

    go基础类 1. go优势 * 天生支持并发,性能高 * 单一的标准代码格式,比其它语言更具可读性 * 自动垃圾收集比java和python更有效,因为它与程序同时执行 go数据类型 int stri ...

随机推荐

  1. jquery如何获取type=hidden的input元素的值?

    function setHiddenFields() { var hiddens = $("input:hidden"); $.each(hiddens, function (in ...

  2. 用于把List<Object>转换成Map<String,Object>形式

    /** * 用于把List<Object>转换成Map<String,Object>形式,便于存入缓存 * @author zhang_bo * @param keyName ...

  3. HDU1811 拓扑排序判环+并查集

    HDU Rank of Tetris 题目:http://acm.hdu.edu.cn/showproblem.php?pid=1811 题意:中文问题就不解释题意了. 这道题其实就是一个拓扑排序判圈 ...

  4. iOS 常用框架介绍

    iOS框架介绍      Cocoa Touch   GameKit  实现对游戏中心的支持,让用户能够在线共享他们的游戏相关的信息  iOS设备之间蓝牙数据传输   从iOS7开始过期   局域网游 ...

  5. UITextView 的 return响应事件

    在UITextView里没有UITextField里的- (BOOL)textFieldShouldReturn:(UITextField *)textField;直接的响应事件;那么在TextVie ...

  6. getResource()和getResourceAsStream以及路径问题(转)

    用JAVA获取文件,听似简单,但对于很多像我这样的新人来说,还是掌握颇浅,用起来感觉颇深,大常最经常用的,就是用JAVA的File类,如要取得c:/test.txt文件,就会这样用File file ...

  7. Ubuntu 分区以及各个挂载目录的基本含义

    我磁盘大概还有70多G的空间吧,我全部拿来使用的.真实的双系统哦. 一般来讲,linux系统分区最少要包括/和/swap两个.这样据说会影响性能,没有这样安装过,就无从考证啦.其实就是重装系统的时候, ...

  8. 剑指Offer——二叉树中和为某一值的路径

    题目描述: 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径. 分析: 先序遍历二叉树,找到二叉树中结点值的和 ...

  9. luarocks安装以及lfs安装

    一.先安装lua: brew install lua 我本机的安装路径为:/usr/local/Cellar/lua/5.3.4_2 二.安装luarocks 下载luarocks的安装包: http ...

  10. 入木三分学网络第一篇--VRRP协议详解第一篇(转)

    因为keepalived使用了VRRP协议,所有有必要熟悉一下. 虚拟路由冗余协议(Virtual Router Redundancy Protocol,简称VRRP)是解决局域网中配置静态网关时,静 ...