-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_test.go
76 lines (61 loc) · 2.44 KB
/
service_test.go
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
package service_test
import (
"github.com/nerdyc/testable-golang-web-service"
"github.com/nerdyc/testable-golang-web-service/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
"net/http"
)
// Test_AddContact shows how to structure a basic service test. Notice the 'SETUP', 'TEST', and 'VERIFY' steps that
// nearly all tests should have.
func Test_AddContact(t *testing.T) {
// SETUP:
// A standard Env. defer is used to ensure the env is cleaned up after the test.
env := test.SetupEnv(t)
defer env.Close()
// TEST: Adding a contact via the API.
contact, err := env.Client.AddContact(service.AddContactRequest{
Email: "[email protected]",
Name: "Alice Zulu",
})
// VERIFY: Response contains the contact
require.NoError(t, err, "Unable to get contact via API")
require.NotEmpty(t, contact, "Contact not found")
assert.True(t, contact.Id > 0, "Contact ID is missing")
assert.Equal(t, contact.Email, "[email protected]")
assert.Equal(t, contact.Name, "Alice Zulu")
// VERIFY: Contact is added to the database properly.
dbContact := env.ReadContactWithEmail("[email protected]")
require.NotEmpty(t, dbContact, "Contact not found")
assert.Equal(t, dbContact.Email, "[email protected]")
assert.Equal(t, dbContact.Name, "Alice Zulu")
}
func Test_GetContactByEmail(t *testing.T) {
env := test.SetupEnv(t)
defer env.Close()
// SETUP:
env.SetupContact("[email protected]", "Alice Zulu")
// -------------------------------------------------------------------------------------------------------------
// TEST: when contact exists
{
// Using braces like this can help isolate different test cases.
contact, err := env.Client.GetContactByEmail("[email protected]")
// VERIFY: Response contains the contact
require.NoError(t, err, "Unable to get contact via API")
require.NotEmpty(t, contact, "Contact not found")
assert.True(t, contact.Id > 0, "Contact ID is missing")
assert.Equal(t, contact.Email, "[email protected]")
assert.Equal(t, contact.Name, "Alice Zulu")
}
// -------------------------------------------------------------------------------------------------------------
// TEST: when contact doesn't exist
{
contact, err := env.Client.GetContactByEmail("[email protected]")
// VERIFY: 404 Not Found returned
require.Error(t, err)
require.IsType(t, service.ErrorResponse{}, err)
assert.Equal(t, http.StatusNotFound, err.(service.ErrorResponse).StatusCode)
assert.Nil(t, contact)
}
}