Testing
References: Examples
Rules
| Rule | Value |
|---|---|
| Unit tests | TestFunctionName |
| Integration tests | TestIntegration* |
| Coverage | 85% minimum |
| Tools | testify/assert, gomock |
Mock Generation
Add at top of file with interfaces:
go
//go:generate mockgen -source=service.go -destination=service_mock.go -package=<pkg>
Run with:
bash
make generate
Table-Driven Tests
Use for testing multiple scenarios:
go
func TestFunction(t *testing.T) {
tests := []struct {
name string
input string
expected string
wantErr bool
}{
{name: "valid input", input: "foo", expected: "bar"},
{name: "empty input", input: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// test logic
})
}
}
Mock Setup
go
func TestService(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockRepo := mocks.NewMockRepository(ctrl)
mockRepo.EXPECT().
FindByID(gomock.Any(), "id").
Return(&Entity{}, nil)
svc := NewService(mockRepo)
// test...
}
Assertions
Use testify/assert:
go
assert.NoError(t, err) assert.Equal(t, expected, actual) assert.Nil(t, result) assert.NotNil(t, result) assert.True(t, condition) assert.Contains(t, slice, element)