Post

Day14(testing)

testing

Golang 自带了一个轻量级的测试框架,可以用来编写单元测试和基准测试。该测试框架主要包含了以下几个组件:

  1. testing.T 结构体:代表了一个单元测试,它包含了一系列断言函数,用于判断测试结果是否正确;
  2. testing.B 结构体:代表了一个基准测试,它用于测试代码的性能;
  3. testing.M 结构体:代表了一个测试 suite,可以用于对一组测试进行分组;
  4. testing.TB 接口:是 testing.T 和 testing.B 的父接口,提供了一些公共的方法,比如 Log、Fail 等。

测试框架提供了一系列的函数,用于编写测试用例和基准测试,例如:

  1. func TestXxx(*testing.T):用于编写单元测试,其中 Xxx 是测试函数的名称;
  2. func BenchmarkXxx(*testing.B):用于编写基准测试,其中 Xxx 是测试函数的名称;
  3. func Example():用于编写示例代码,用于生成文档。

下面是一个简单的示例,演示了如何使用 testing.T 编写单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Add(2, 3) = %d, expected %d", result, expected)
    }
}

func Add(a, b int) int {
    return a + b
}

在上面的代码中,我们定义了一个 Add() 函数,它接收两个整数参数,并返回它们的和。然后,我们使用 TestAdd() 函数编写了一个单元测试,其中通过调用 Add() 函数来计算 2 + 3 的结果,并使用 t.Errorf() 函数来判断计算结果是否等于期望结果。

我们可以通过运行 go test 命令来运行这个测试,例如:

1
2
3
4
5
6
$ go test -v
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok      _/home/user/example    0.001s

This post is licensed under CC BY 4.0 by the author.