Search code examples
amazon-web-servicesunit-testinggointerface

Golang: mocking AWS services which have same method name


I'm using two AWS services, Glue and DynamoDB and both of these services, have a same method name CreateTable so while mocking these services, I'm getting CreateTable is ambiguous error.

Glue: CreateTable https://docs.aws.amazon.com/sdk-for-go/api/service/glue/#Glue.CreateTable

DynamoDB: CreateTable https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.CreateTable

Is there any way to resolve this issue?

Code:

type UpdateWorkflow struct {
    glueIface glueiface.GlueAPI
    dbIface   dynamodbiface.DynamoDBAPI
    tableName string
}

func NewUpdateWorkflow(tableName string) *UpdateWorkflow {
    sess := sessions.NewSession()
    return &UpdateWorkflow{
        dbIface:   dynamodb.New(sess),
        glueIface: glue.New(sess),
        tableName: tableName,
    }
}

Unit test:

// MockUpdateWorkflow is a mock implementation of gluetestutils and dynamodb service
type MockUpdateWorkflow struct {
    glueiface.GlueAPI
    dynamodbiface.DynamoDBAPI
    mock.Mock
}

func setup() (*UpdateWorkflow, *MockUpdateWorkflow) {
    mockClient := new(MockUpdateWorkflow)
    mockServices := &UpdateWorkflow{
        glueIface: mockClient,
        dbIface:   mockClient,
        tableName: mockTableName,
    }
    return mockServices, mockClient
}

Solution

  • If there are conflicting function names, you cannot embed interfaces, you have to use named fields:

    type MockUpdateWorkflow struct {
        g glueiface.GlueAPI
        d dynamodbiface.DynamoDBAPI
        mock.Mock
    }
    
    func setup() (*UpdateWorkflow, *MockUpdateWorkflow) {
        mockClient := new(MockUpdateWorkflow)
        mockServices := &UpdateWorkflow{
            glueIface: mockClient.g,
            dbIface:   mockClient.d,
            tableName: mockTableName,
        }
        return mockServices, mockClient
    }