只运行单个测试,而不是整个套件?

我有一个 Go 包的测试套件,它实现了十几个测试。有时候,套件中的一个测试失败了,我想单独重新运行那个测试,以节省调试过程中的时间。这可能吗? 还是每次都要写一个单独的文件?

87308 次浏览

Use the go test -run flag to run a specific test. The flag is documented in the testing flags section of the go tool documentation:

-run regexp
Run only those tests and examples matching the regular
expression.

In case someone that is using Ginkgo BDD framework for Go will have the same problem, this could be achieved in that framework by marking test spec as focused (see docs), by prepending F before It, Context or Describefunctions.

So, if you have spec like:

    It("should be idempotent", func() {

You rewrite it as:

    FIt("should be idempotent", func() {

And it will run exactly that one spec:

[Fail] testing Migrate setCurrentDbVersion [It] should be idempotent
...
Ran 1 of 5 Specs in 0.003 seconds
FAIL! -- 0 Passed | 1 Failed | 0 Pending | 4 Skipped

Given a test:

func Test_myTest() {
//...
}

Run only that test with:

go test -run Test_myTest path/to/pkg/mypackage

Say your test suite is structured as following:

type MyTestSuite struct {
suite.Suite
}


func TestMyTestSuite(t *testing.T) {
suite.Run(t, new(MyTestSuite))
}


func (s *MyTestSuite) TestMethodA() {
}

To run a specific test of test suite in go, you need to use: -testify.m.

 go test -v <package> -run ^TestMyTestSuite$ -testify.m TestMethodA

More simply, if the method name is unique to a package, you can always run this

go test -v <package> -testify.m TestMethodA

Simple and reliable:

go test -run TestMyFunction ./...

More on ./... : https://stackoverflow.com/a/28031651/5726621

go test -v <package> -run <TestFunction>