gpt4 book ai didi

go - 在 TestMain 中使用 testing.T

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:30 24 4
gpt4 key购买 nike

我想运行一些测试用例,需要启动 GRPC 模拟服务器。为此,我正在使用 gomock 库。要启动服务器,我必须将类型为 testing.T 的变量传递给此函数 - gomock.NewController() .由于这是对所有测试用例的一种初始化,我想在 TestMain 中执行此操作。但是 TestMain 只能访问 testing.M 那么我该如何处理这种情况呢?在 TestMain 中创建一个新的 testing.T 结构?会成功吗?

最佳答案

听起来您正在寻找 BeforeEach 模式。您无权访问 TestMain 中的 testing.T 对象,因为这是在测试套件运行前后进行初始化的更多地方。

有一些框架可以为您提供便宜的 BeforeEach:

仅举几例。

你也可以自己手卷:

type test struct{
ctrl *gomock.Controller
mockFoo *MockFoo
// ...
}

func beforeEach(t *testing.T) test {
ctrl := gomock.NewController(t)
return test {
ctrl:ctrl,
mockFoo: NewMockFoo(ctrl),
}
}

func TestBar(t *testing.T) {
test := beforeEach(t)
// ...
}

func TestBaz(t *testing.T) {
test := beforeEach(t)
// ...
}

关于go - 在 TestMain 中使用 testing.T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com