我可以创建共享的测试实用程序吗? [英] Can I create shared test utilities?

查看:50
本文介绍了我可以创建共享的测试实用程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在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中:

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和其他程序包可以使用该共享库来设置测试服务器和客户端以对其进行测试.例如,在handler子软件包中,我有:

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

handler/*_test.go文件全部导入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]

看来测试可以导入其他程序包,但不能导入那些程序包中定义的测试代码?这是意图吗?如果是这样,是否有一种惯用的方式可以在go中跨软件包共享测试实用程序?

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

Create a package containing the testing utilities in non _test.go files. A couple of examples of this approach are httptest and iotest.

这篇关于我可以创建共享的测试实用程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆