Generating mocks for AWS Go SDK

Krzysztof
Flow Lab
Published in
1 min readJun 18, 2019

--

One way to generate mocks for AWS SDK is to use mockgen with go generate command.

Example below shows generating the mock for CloudWatchLogsAPI and placing mock into mocks directory.

package cloudwatchlogs

import (
"github.com/golang/mock/gomock"
"github.com/flowlab/log/pkg/mocks"
"testing"
)

//go:generate mockgen -package=mocks -destination ../mocks/mock_cloudwatchlogsiface.go github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface CloudWatchLogsAPI

func TestPutRetentionPolicy(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockCloudWatchLogsAPI := mocks.NewMockCloudWatchLogsAPI(ctrl)

mockCloudWatchLogsAPI.EXPECT().
PutRetentionPolicyWithContext(gomock.Any(), gomock.Any()).
Return(nil, nil).
Times(1)
// test code and assertions
}

go generate is not part of go build. It contains no dependency analysis and must be run explicitly before running go build.

--

--