I want to add custom flags for my Go tests that use testify/suite. It looks like from this thread that it can only be in TestMain() (init() if it is before Go 1.13). However, with the testify/suite pacakge, TestMain() is not quite an option. I have tried declaring the flags in SeupSuite() and TestMyTestSuite() which seems to be a corresponding TestMain() but both returned the error flag provided but not defined: -mycustomflag. Below is the sample code. Any suggestion will be appreciated!
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")
}
This is the command I used:
go test my_test.go -mycustomflag
The test binary generated by
go testis already using theflagpackage internally and callsflag.Parse()during normal operation. Define the flag variable as global (✳️) so they are known before runningflag.Parse().To
runtest separately in the package, create a file for thepackagecontains only with requiredflag(✳️) and compile singletestwith file, which containsflagsflag_test.goalso you can
runall tests with requiredflag