如何在测试中使用自定义标志(使用"testify/suite")



我想为使用testify/suite的Go测试添加自定义标志。从这个线程来看,它只能在TestMain()中(如果它在 Go 1.13 之前,则init())。但是,对于作证/套件包,TestMain()不是一个选择。我尝试在SeupSuite()TestMyTestSuite()中声明标志,这似乎是相应的TestMain()但都返回了错误flag provided but not defined: -mycustomflag。下面是示例代码。任何建议将不胜感激!

my_test.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: %tn", *flagBoolPtr)
}
func TestMyTestSuite(t *testing.T) {
fmt.Printf("my flag in test: %tn", *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() 的package创建一个文件,并使用包含flags✳️ 的文件编译单个test

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

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

您还可以使用所需的flagrun所有测试

go test -v ./... -mycustomflag

最新更新