1// +build example
2
3// Unit tests for package unitTest.
4package unitTest
5
6import (
7	"errors"
8	"testing"
9
10	"github.com/aws/aws-sdk-go/aws"
11	"github.com/aws/aws-sdk-go/service/dynamodb"
12	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
13)
14
15// A fakeDynamoDB instance. During testing, instatiate ItemGetter, then simply
16// assign an instance of fakeDynamoDB to it.
17type fakeDynamoDB struct {
18	dynamodbiface.DynamoDBAPI
19	payload map[string]string // Store expected return values
20	err     error
21}
22
23// Mock GetItem such that the output returned carries values identical to input.
24func (fd *fakeDynamoDB) GetItem(input *dynamodb.GetItemInput) (*dynamodb.GetItemOutput, error) {
25	output := new(dynamodb.GetItemOutput)
26	output.Item = make(map[string]*dynamodb.AttributeValue)
27	for key, value := range fd.payload {
28		output.Item[key] = &dynamodb.AttributeValue{
29			S: aws.String(value),
30		}
31	}
32	return output, fd.err
33}
34
35func TestItemGetterGet(t *testing.T) {
36	expectedKey := "expected key"
37	expectedValue := "expected value"
38	getter := new(ItemGetter)
39	getter.DynamoDB = &fakeDynamoDB{
40		payload: map[string]string{"id": expectedKey, "value": expectedValue},
41	}
42	if actualValue := getter.Get(expectedKey); actualValue != expectedValue {
43		t.Errorf("Expected %q but got %q", expectedValue, actualValue)
44	}
45}
46
47// When DynamoDB.GetItem returns a non-nil error, expect an empty string.
48func TestItemGetterGetFail(t *testing.T) {
49	expectedKey := "expected key"
50	expectedValue := "expected value"
51	getter := new(ItemGetter)
52	getter.DynamoDB = &fakeDynamoDB{
53		payload: map[string]string{"id": expectedKey, "value": expectedValue},
54		err:     errors.New("any error"),
55	}
56	if actualValue := getter.Get(expectedKey); len(actualValue) > 0 {
57		t.Errorf("Expected %q but got %q", expectedValue, actualValue)
58	}
59}
60