4

There are a few test cases I want to run for which there is a need to start a GRPC mock server. I am using gomock library for this. To start the server, I have to pass a variable of type testing.T to this function - gomock.NewController(). Since this is a kind of initialization for all the test cases, I want to do this in TestMain. But TestMain has access to only testing.M So how do I handle this case? Create a new testing.T structure in TestMain? Will it work?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
aniztar
  • 2,443
  • 4
  • 18
  • 24
  • 1
    As TestReporter is only an interface, you may try to create yours: https://github.com/golang/mock/issues/122#issuecomment-338743825 – Berkant İpek Nov 03 '18 at 07:31
  • 4
    You can't create a testing.T instance because all fields are not exported. Forget about TestMain and start the server in each test individually. That's best practice in general. – Peter Nov 03 '18 at 07:37
  • please provide some code example of your main function. I am sure you have too much things inside. With a little refactoring of your main function the testing will be then much easier. – apxp Nov 03 '18 at 10:10

1 Answers1

5

It sounds like you are looking for a BeforeEach pattern. You don't have access to a testing.T object in TestMain because this is something more of a place to do initialization before and after the test suite runs.

There are a few frameworks out there that can give you a BeforeEach cheap:

to name a few.

You could also hand roll your own:

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)
  // ...
}
poy
  • 10,063
  • 9
  • 49
  • 74