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?
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)
// ...
}