如何在指定文件中运行测试用例? [英] How to run test cases in a specified file?
问题描述
我的包测试用例分散在多个文件中,如果我运行 go test
它会运行包中的所有测试用例.
My package test cases are scattered across multiple files, if I run go test <package_name>
it runs all test cases in the package.
虽然没有必要运行所有这些.有没有办法指定一个文件让 go test
运行,让它只运行文件中定义的测试用例?
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?
推荐答案
有两种方法.最简单的方法是使用 -run
标志并提供一个模式匹配您要运行的测试的名称.示例:
There are two ways. The easy one is to use the -run
flag and provide a
pattern matching names of the tests you want to run. Example:
go test packageName -run NameOfTest
有关详细信息,请参阅文档.请注意,-run
标志也可能运行其他包含字符串的测试NameOfTest
,因为 -run
标志匹配正则表达式.所以为了确保只有一个运行名为NameOfTest"的测试,必须使用正则表达式 ^NameOfTest$
:
See 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 -v foo_test.go
但是有一个问题.这在以下情况下运行良好:
But there's a catch. This works well if:
foo.go
在package foo
中.foo_test.go
在package foo_test
中并导入 'foo'.
foo.go
is inpackage foo
.foo_test.go
is inpackage foo_test
and imports 'foo'.
如果 foo_test.go
和 foo.go
是同一个包(常见情况),那么你必须命名构建 foo_test
所需的所有其他文件.在这个例子中将是:
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.go
我建议使用 -run
模式.或者,在可能的情况下,始终运行所有包测试.
I'd recommend to use the -run
pattern. Or, where/when possible, always run
all package tests.
这篇关于如何在指定文件中运行测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!