1

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

4

1 回答 1

3

听起来您正在寻找一种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)
  // ...
}
于 2018-12-03T17:05:58.353 回答