[英]Trying to run tests in parallel with golang testify/suite fails
[英]How to use custom flag with testify/suite in Go test
我想为使用 testify/suite 的 Go 测试添加自定义标志。 从这个线程看来,它只能在TestMain()
中(如果它在 Go 1.13 之前,它只能在init()
中)。 然而,对于 testify/suite 包, 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
package 并在正常操作期间调用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.