-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
92 lines (77 loc) · 2.15 KB
/
example_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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package hex_test
import (
"fmt"
"net/http"
"net/url"
"testing"
"github.com/meagar/hex"
)
// MockUserService is a mock we dependency-inject into our Client library
// It embeds a hex.Server so we can make HTTP requests of it, and use ExpectReq to set up
// HTTP expectations.
type MockUserService struct {
*hex.Server
}
func NewMockUserService(t *testing.T) *MockUserService {
s := MockUserService{}
s.Server = hex.NewServer(t, &s)
return &s
}
func (m *MockUserService) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
path := req.Method + " " + req.URL.Path
switch path {
case "GET /users":
// TODO: Generate the response a client would expect
case "POST /users":
// TODO: Generate the response a client would expect
default:
rw.WriteHeader(http.StatusNotFound)
fmt.Fprintf(rw, "Not found")
}
}
// SearchClient is our real HTTP client for the given service
type UsersClient struct {
Host string
Client *http.Client
}
type User struct {
Name string
Email string
}
// Search hits the "search" endpoint for the given host, with an id query string parameter
func (c *UsersClient) Find(userID int) (User, error) {
_, err := c.Client.Get(fmt.Sprintf("%s/users/%d", c.Host, userID))
// TODO: Decode mock service response
return User{}, err
}
func (c *UsersClient) Create(u User) error {
data := url.Values{}
data.Set("name", u.Name)
data.Set("email", u.Email)
_, err := c.Client.PostForm(c.Host+"/users", data)
return err
}
func Example() {
t := testing.T{}
service := NewMockUserService(&t)
// Client is our real client implementation
client := UsersClient{
Client: service.Client(),
Host: service.URL,
}
// Make expectations about the client library
service.ExpectReq("GET", "/users/123").Once().Do(func() {
client.Find(123)
})
service.ExpectReq("POST", "/users").WithBody("name", "User McUser").WithBody("email", "user@example.com").Do(func() {
client.Create(User{
Name: "User McUser",
Email: "user@example.com",
})
})
fmt.Println(service.Summary())
// Output:
// Expectations
// GET /users/123 - passed
// POST /users with body matching name="User McUser"body matching email="user@example.com" - passed
}