我正在为 http 服务编写组件测试。我有一个测试运行程序类,其中包含一些有用的结构和共享函数(主要是“进行 http 调用”和“比较 json 结构”)。该测试运行器类需要具有从 envvars 中提取的用于发送 http 调用的域。我不想每次进行 http 调用时都从环境变量中获取域,而是更愿意解析一次并将其设置在测试运行器类的实例中,然后让该实例可用于我的所有测试函数。< /p>
假设测试函数的预期签名是 func TestXxx(t *testing.T) {...}
我怎样才能使这个实例可用于我的测试?
代码:
使用包级变量来存储值。初始化访问器函数中的值。使用sync.Once确保初始化完成一次。
type Helper struct { message string } var ( helper *Helper helperOnce sync.Once ) func getHelper() *Helper { helperOnce.Do(func() { helper = &Helper{"Hello"} }) return helper } func TestFirst(t *testing.T) { h := getHelper() t.Log(h.message) } func TestSecond(t *testing.T) { h := getHelper() t.Log(h.message) }