Skip to content

Instantly share code, notes, and snippets.

@jboursiquot
Last active January 20, 2020 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jboursiquot/1784ad14fbd2037197400053c3f41b84 to your computer and use it in GitHub Desktop.
Save jboursiquot/1784ad14fbd2037197400053c3f41b84 to your computer and use it in GitHub Desktop.
Baltimore Go User Group - Interface & Testing mini-workshop

Working with Interfaces

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
@jboursiquot
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment