snippetgoCritical
How to run test cases in a specified file?
Viewed 0 times
runhowspecifiedfilecasestest
Problem
My package test cases are scattered across multiple files, if I run
It is unnecessary to run all of them though. Is there a way to specify a file for
go test it runs all test cases in the package.It is unnecessary to run all of them though. Is there a way to specify a file for
go test to run, so that it only runs test cases defined in the file?Solution
There are two ways. The easy one is to use the
Example:
See the docs for more info.
Note that the
So to ensure that only a test named exactly 'NameOfTest' is run,
one has to use the regexp
The other way is to name the specific file, containing the tests you want to run:
But there's a catch. This works well if:
If
I'd recommend to use the
-run flag and provide a pattern matching names of the tests you want to run.Example:
$ go test packageName -run NameOfTestSee the docs for more info.
Note that the
-run flag may also run other tests if they contain the string NameOfTest, as the -run flag matches a regexp.So to ensure that only a test named exactly 'NameOfTest' is run,
one has to use the regexp
^NameOfTest$:$ go test -run "^NameOfTest$"The other way is to name the specific file, containing the tests you want to run:
$ go test foo_test.goBut there's a catch. This works well if:
foo.gois inpackage foo.
foo_test.gois inpackage foo_testand imports 'foo'.
If
foo_test.go and foo.go are the same package (a common case) then you must name all other files required to build foo_test. In this example it would be:$ go test foo_test.go foo.goI'd recommend to use the
-run pattern. Or, where/when possible, always run all package tests.Code Snippets
$ go test packageName -run NameOfTest$ go test -run "^NameOfTest$"$ go test foo_test.go$ go test foo_test.go foo.goContext
Stack Overflow Q#16935965, score: 557
Revisions (0)
No revisions yet.