我可以创建共享测试实用程序吗? [英] Can I create shared test utilities in go?
问题描述
我想知道是否可以在包中分享测试实用程序代码。具体来说,我正在编写一个TCP服务器,它将被多个处理程序用于不同的消息类型,并且希望重用一组常见的测试实用程序。
I'm wondering whether it's possible to share test utility code across packages in go. Specifically, I'm writing a TCP server that will be used by multiple handlers for different message types, and want to reuse a set of common test utils.
主TCP服务器代码位于 mypkg / tcpserver
中:
$ b
The main TCP server code is in mypkg/tcpserver
:
mypkg/tcpserver/tcp_server.go
mypkg/tcpserver/tcp_server_test.go
mypkg/tcpserver/testutils_test.go
testutils_test.go
代码旨在成为共享库,可由 mypkg / tcpserver
使用,其他软件包为他们的测试设置测试服务器和客户端。例如,在处理程序
子包中,我有:
The testutils_test.go
code is intended to be a shared library that can be used by mypkg/tcpserver
and other packages to set up a test server and client for their tests. For example in the handler
subpackage I have:
mypkg/tcpserver/handler/handler.go
mypkg/tcpserver/handler/csv_handler.go
mypkg/tcpserver/handler/csv_handler_test.go
mypkg/tcpserver/handler/delim_handler.go
mypkg/tcpserver/handler/delim_handler_test.go
处理程序/ * _ test.go
files all import mypkg / tcpserver
,但它们无法访问 mypkg / tcpserver / testutils_test.go中定义的测试实用程序
:
The handler/*_test.go
files all import mypkg/tcpserver
, but they are unable to access the test utilities defined in mypkg/tcpserver/testutils_test.go
:
$ wgo test mypkg/tcpserver/handler
# mypkg/tcpserver/handler
src/mypkg/tcpserver/handler/csv_handler_test.go:37: undefined: tcpserver.CreateTestServer
src/mypkg/tcpserver/handler/csv_handler_test.go:40: undefined: tcpserver.TestSender
FAIL mypkg/tcpserver/handler [build failed]
看来测试可以导入其他包,但不能测试代码在这些软件包中定义?这是意图吗?如果是这样,是否有一种惯用的方式来共享包中的测试实用程序?
It appears that tests can import other packages, but not test code defined within those packages? Is this the intent? If so, is there an idiomatic way to share test utilities across packages in go?
推荐答案
创建一个包含测试实用程序的包非_test.go文件。这种方法的一些例子是 httptest 和 iotest 。
Create a package containing the testing utilities in non _test.go files. A couple of examples of this approach are httptest and iotest.
这篇关于我可以创建共享测试实用程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!