Skip to content

Instantly share code, notes, and snippets.

@dimroc
Last active November 19, 2018 22:35
Show Gist options
  • Save dimroc/3d67cf9aa790276deba0cafd4ba56060 to your computer and use it in GitHub Desktop.
Save dimroc/3d67cf9aa790276deba0cafd4ba56060 to your computer and use it in GitHub Desktop.
Finding it hard to shoe horn into table driven tests
func TestHeightsController_Index(t *testing.T) {
threshold := big.NewInt(2)
tests := []struct {
name string
status int
}{
{"good clients", 200},
// Hard to do error cases without adding an if with difference setup. could add test helpers...
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient1 := mocks.NewMockclient(ctrl)
mockClient2 := mocks.NewMockclient(ctrl)
// Below I'm mocking as verb :(
mockClient1.EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any())
mockClient1.EXPECT().Endpoint()
mockClient2.EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any())
mockClient2.EXPECT().Endpoint()
c, _ := gin.CreateTestContext(httptest.NewRecorder())
hc := heightsController{
threshold: threshold,
client1: mockClient1,
client2: mockClient2,
}
hc.Index(c)
require.Equal(t, test.status, c.Writer.Status())
})
}
}
func TestHeightsController_Index(t *testing.T) {
threshold := big.NewInt(2)
tests := []struct {
name string
client1, client2 client
status int
}{
{"bad client 1", clientErrorMock{}, clientMock{}, 502},
{"bad client 2", clientErrorMock{}, clientMock{}, 502},
{"good clients", clientMock{}, clientMock{}, 200},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
hc := heightsController{
threshold: threshold,
client1: test.client1,
client2: test.client2,
}
hc.Index(c)
require.Equal(t, test.status, c.Writer.Status())
})
}
}
// mocks as noun
type clientMock struct{}
func (clientMock) Call(result interface{}, method string, args ...interface{}) error { return nil }
func (clientMock) Endpoint() string {
return "http://clientmock.com"
}
type clientErrorMock struct{}
func (clientErrorMock) Call(result interface{}, method string, args ...interface{}) error {
return errors.New("clientErrorMock")
}
func (clientErrorMock) Endpoint() string {
return "http://clienterrormock.com"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment