我想为使用证言/套件的GO测试添加自定义标志.从这个thread看,它只能在TestMain()(如果在GO 1.13之前是init()).然而,对于证言/套房包,TestMain()不是一个很好的 Select .我try 声明SeupSuite()TestMyTestSuite()中的标志,它们似乎是对应的TestMain(),但都返回了错误flag provided but not defined: -mycustomflag.以下是示例代码.任何建议都将不胜感激!

我的测试.go :

package main

import (
    "flag"
    "fmt"
    "github.com/stretchr/testify/suite"
    "testing"
)

type MyTestSuite struct {
    suite.Suite
}

func (suite *MyTestSuite) SetupSuite() {
    flagBoolPtr := flag.Bool("mycustomflag", false, "this is a bool flag")
    flag.Parse()
    fmt.Printf("my flag is set to: %t", *flagBoolPtr)
}

func TestMyTestSuite(t *testing.T) {
    // flagBoolPtr := flag.Bool("mycustomflag", false, "this is a bool flag")
    // flag.Parse()
    // fmt.Printf("my flag is set to: %t", *flagBoolPtr)
    suite.Run(t, new(MyTestSuite))
}

func (suite *MyTestSuite) TestBuildClosure() {
    fmt.Println("my test")
}

这是我使用的命令:

go test my_test.go -mycustomflag

推荐答案

go test生成的测试二进制文件已经在内部使用flag包,并在正常操作期间调用flag.Parse(). 将标志变量定义为全局变量(✳️),以便在运行flag.Parse()时知道它们.

type MyTestSuite struct {
    suite.Suite
}

// ✳️
var flagBoolPtr = flag.Bool("mycustomflag", false, "this is a bool flag")

func (suite *MyTestSuite) SetupSuite() {
    fmt.Printf("my flag in SetupSuite: %t\n", *flagBoolPtr)
}

func TestMyTestSuite(t *testing.T) {
    fmt.Printf("my flag in test: %t\n", *flagBoolPtr)
    suite.Run(t, new(MyTestSuite))
}

func (suite *MyTestSuite) TestBuildClosure() {
    fmt.Println("my test")
}

go test -v my_test.go -mycustomflag

=== RUN   TestMyTestSuite
my flag in test: true
my flag in SetupSuite: true
=== RUN   TestMyTestSuite/TestBuildClosure
my test
--- PASS: TestMyTestSuite (0.00s)
    --- PASS: TestMyTestSuite/TestBuildClosure (0.00s)
PASS

但是,如果我在同一个包中有多个测试套件,即多个文件,该怎么办呢?我想把这面旗帜用在所有的测试服上?由于我们只能定义变量和标志一次,如何才能确保此特定测试套件中的声明首先被执行?

要在包中单独测试run,只需创建一个包含flag的文件(✳️),并编译单个包含flagstest文件

.
├── my_test.go
├── other_my_test.go
└── flag_test.go // ✳️

GB flag_test.go

package any

import "flag"

var flagBoolPtr = flag.Bool("mycustomflag", false, "this is a bool flag")
go test -v flag_test.go my_test.go -mycustomflag

此外,您还可以使用所需的flag进行所有测试

 go test -v ./... -mycustomflag

Go相关问答推荐

如何使用Docker Compose配置Go,使main. go文件位于/CMD文件夹中

将类型定义为泛型类型实例化

Kafka golang 生产者在错误后更改分区计数

在VSCode中如何使用特定的文件名提供编译命令

在 Windows 11 上运行 go mod tidy 时的 gitlab 权限问题

杜松子wine 和中间件

Opensearch 错误 ping 弹性服务器:由未知权威签署的 x509 证书

尽管存在 WaitGroup,Goroutines 似乎被打断了

创建新对象后如何返回嵌套实体?

在嵌套模板中使用变量,它也被定义为 go 模板中的变量?

GOLANG:为什么 SetDeadline/SetReadDeadline/SetWriteDeadline 在使用 os.File.Fd() 时对文件不起作用?

Golang - 客户 Unmarshaler/Marshaler 在指针上具有 nil/null 值

如何使用 Go 获取 X11 中的窗口列表

github.com/rs/zerolog 字段的延迟判断

try 运行 docker-compose up -d 时出现错误

如何在Golang中的差异函数中杀死命令Exec

如何在gin中获取参数值数组

HCL 解码:具有多个标签的块

我该如何做错误处理惯用的方式

如何将类型转换为字节数组golang