go - 在 TestMain 中使用 testing.T

标签 go grpc gomock

我想运行一些测试用例,需要启动 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/

相关文章:

google-app-engine - goapp 二进制文件在哪里?

go - 在一个 Go 应用程序中提供 gRPC 和 Restful 服务

go - 如何处理随机输入输出值

google-app-engine - 在 Go 中合并独立的 webapp 和 GAE

Golang 不处理 2 个操作

调用 Go RPC TCP 服务时 Ruby Socket 客户端挂起

java - 在 gRPC 中使用直接类以避免数据复制

go - 如何在 go 模型中包装 proto 消息

unit-testing - 如何只模拟接口(interface)的一种方法

go - 模拟非接口(interface)函数