【问题标题】:go test: only run tests that contain a build tag?go test:只运行包含构建标签的测试?
【发布时间】:2021-05-31 22:15:28
【问题描述】:

我有一组长时间运行的测试,用构建标签定义。例如,

// file some_test.go
//+build func_test

(rest of file with test cases)

我还有许多其他较短的运行测试,没有这个构建标志。 有没有一种方法可以轻松地只运行包含构建标签“func_test”的测试?

请注意,如果我只运行 go test -tags func_test,它会运行所有测试,包括 some_test.go 中的测试。

【问题讨论】:

  • 显然添加更多测试并不会阻止现有测试运行您需要按名称或约束排除其他测试,选择权在您手中。

标签: go testing


【解决方案1】:

根据 golang 文档https://golang.org/pkg/go/build/

构建标签列出了文件应包含在包中的条件。因此,如果您只想为构建标签 func_test 运行测试,那么您需要为其他测试提供不同的标签。

这是一个例子: 我的测试目录中有以下 2 个测试文件。

func_test.go

//+build test_all func_test

package go_build_test

import (
    "fmt"
    "testing"
)

func TestNormal(t *testing.T) {
    fmt.Println("testing:", t.Name())

}

other_test.go

//+build test_all,!func_test

package go_build_test

import "testing"
import "fmt"

func TestOtherCase(t *testing.T) {
    fmt.Println("testing:", t.Name())
}

现在,如果您想运行所有测试。

$ go test -tags=test_all
testing: TestNormal
testing: TestOtherCase
PASS
ok      _/D_/Project/ARC/source/prototype/go/src/go-build-test  0.186s

只运行 func_test

$ go test -tags=func_test
testing: TestNormal
PASS
ok      _/D_/Project/ARC/source/prototype/go/src/go-build-test  1.395s

诀窍是使用带有 AND/OR 条件的 //+build 注释。

【讨论】:

  • 是的,这就是我害怕的。这意味着我们所有编写单元测试的开发人员都需要了解这个名为“test_all”的新标签
【解决方案2】:

您可以按照约定命名您的测试。 即让您的长时间运行的测试功能以TestLong_ 开头 然后运行它们 go test ./... -run TestLong -tags func_test

【讨论】:

    【解决方案3】:

    -tags 后面需要= 符号

    go test -tags=func_test

    【讨论】:

    • 不,没必要
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2019-05-03
    • 2018-05-17
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多