在TestMain中使用testing.T

时间:2018-11-03 07:23:40

标签: go grpc gomock

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

1 个答案:

答案 0 :(得分:1)

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

有一些框架可以让您便宜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)
  // ...
}