how to use dockertest in golang

Prerequisite

dockertest

1
go get -u github.com/ory/dockertest/v3

How to write testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
type repoSuite struct {
suite.Suite
pool *dockertest.Pool
resource *dockertest.Resource
client *mongo.Client
repo IRepo
}

func (s *repoSuite) SetupTest() {
logger := zap.NewNop()

// new pool by dockertest
pool, err := dockertest.NewPool("")
if err != nil {
panic(err)
}
s.pool = pool

// run resource by image name and env
resource, err := pool.Run("mongo", "4.4.10", nil)
if err != nil {
panic(err)
}
s.resource = resource

err = pool.Retry(func() error {
uri := fmt.Sprintf("mongodb://localhost:%s/", resource.GetPort("27017/tcp"))
s.client, err = mongo.Connect(contextx.Background(), options.Client().ApplyURI(uri))
if err != nil {
return err
}

return s.client.Ping(contextx.Background(), readpref.Primary())
})
if err != nil {
panic(err)
}

repo, err := CreateIRepo(logger, s.client)
if err != nil {
panic(err)
}
s.repo = repo
}

func (s *repoSuite) TearDownTest() {
_ = s.client.Disconnect(contextx.Background())

// purge container
_ = s.pool.Purge(s.resource)
}

func TestRepoSuite(t *testing.T) {
suite.Run(t, new(repoSuite))
}

// test ping mongodb
func (s *repoSuite) Test_impl_PingMongo() {
type args struct {
mock func()
}
tests := []struct {
name string
args args
want bool
wantErr bool
}{
{
name: "ping then success",
args: args{},
want: true,
wantErr: false,
},
}
for _, tt := range tests {
s.T().Run(tt.name, func(t *testing.T) {
if tt.args.mock != nil {
tt.args.mock()
}

got, err := s.repo.PingMongo(contextx.Background())
if (err != nil) != tt.wantErr {
t.Errorf("PingMongo() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("PingMongo() got = %v, want %v", got, tt.want)
}
})
}
}