This exercise challenges you to think about how to use interfaces to mock third party behavior.
Imagine you have a project that needs to interact with AWS DynamoDB. AWS makes available a Go SDK and package for such a purpose: dynamodb.
Your starting point is a package mypackage
containing a custom type DynamoDBSaver
with a Save
method:
package mypackage
type DynamoDBSaver struct {
// dynamodb client here
}
func (s *DynamoDBSaver) Save(ctx context.Context, p *Person) error {
item, err := dynamodbattribute.MarshalMap(p)
if err != nil {
return fmt.Errorf("failed to marshal shoutout for storage: %s", err)
}
input := &dynamodb.PutItemInput{
Item: item,
TableName: aws.String(os.Getenv("TABLE_NAME")),
}
// your code to PutItemWithContext here
}
A value of type Person
is also expected in the Save
call.
type Person struct {
Name string
}
AWS also makes available a package for the DynamoDB API that you can use in your tests: dynamodbiface. Your task is to mock out the DynamoDB API for your DynamoDBSaver
to use in tests.
Hint: Use Go interfaces to mock only what you need.
You will also need to include the dynamodbattrbiute
package in your imports.
Success Criteria:
- You mock the DynamoDB API in your tests
- You test your package from outside of your
mypackage
package (i.e.mypackage_test
) - Bonus: You use table-driven testing technique
Learning Outcomes:
- You know how to set up Go tests
- You know how to work with third party packages
- You know how to use Go interfaces effectively
- You know how to mock only what you need
Sample solution: https://gist.github.com/jboursiquot/331b69a04ed1124d7a82fdc47ee54abc