英文:
How to run 'go test' and include unit test files but exclude other test files
问题
我正在尝试自动化运行现有的Go项目上的单元测试。该项目已经有很多现有的测试,这些测试不仅仅是单元测试,还涉及到与外部服务的联系和对数据库的写入。我想通过使用命名约定来排除这些测试文件的自动化。假设项目的结构如下:
gopath/
|-package1.go
|-package1_unit_test.go
|-package1_e2e_test.go
|-package2/
|-package2.go
|-package2_unit_test.go
|-package2_e2e_test.go
我可以运行 go test ./...
来运行所有的测试。如果我在我的单元测试的名称中包含 'UnitTest',我可以运行 go test ./... -run UnitTest
,但这仍然会运行e2e测试中的启动代码。我需要完全忽略这些文件。有人建议运行 go test $(go list ./... | grep -v /e2e/)
,但是 go list
输出的是目录名,而不是文件名,所以这个方法行不通。
是的,理想情况下,e2e测试应该放在一个不同的目录中,并且不依赖于包的内部实现,但不幸的是,我的同事们并没有这样编写。我现在正在寻找一个快速解决方案!
英文:
I'm trying to automate running unit tests on an existing Go project. It already has a lot of existing tests which do non-unit test things like contact external services and write to databases. I would like to exclude these test files from the automation using a naming convention. Say the structure of the project is like this:
gopath/
|-package1.go
|-package1_unit_test.go
|-package1_e2e_test.go
|-package2/
|-package2.go
|-package2_unit_test.go
|-package2_e2e_test.go
I can run go test ./...
to run all the tests. If I include 'UnitTest' in the names of my unit tests I can run go test ./... -run UnitTest
but this still runs the startup code in the e2e tests. I need it to completely ignore those files. Someone suggested running go test $(go list ./... | grep -v /e2e/)
but go list
outputs directory names, not file names, so that doesn't work.
And yes, ideally the e2e tests should go in a different directory and not rely on the internals of the package but unfortunately that's not how my coworkers wrote them. I'm looking for a quick fix right now!
答案1
得分: 4
你可以使用构建标签来限制构建,包括测试,只针对某个文件的子集进行构建:https://dave.cheney.net/2014/09/28/using-build-to-switch-between-debug-and-release
例如,你可以在集成测试文件的顶部添加//+build integration
,这样只有在运行go test -tags integration
时才会构建和执行这些文件。
英文:
You can use build tags to limit builds, including tests, to a certain subset of files: https://dave.cheney.net/2014/09/28/using-build-to-switch-between-debug-and-release
For example, you could put //+build integration
at the top of your integration test files, and then those would only be built and executed when you run go test -tags integration
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论