forked from jarcoal/httpmock
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdoc.go
More file actions
91 lines (78 loc) · 2.19 KB
/
doc.go
File metadata and controls
91 lines (78 loc) · 2.19 KB
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
/*
Package httpmock provides tools for mocking HTTP responses.
Simple Example:
func TestFetchArticles(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterStubRequest(
httpmock.NewStubRequest(
"GET",
"https://api.mybiz.com/articles.json",
httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`),
),
)
// do stuff that makes a request to articles.json
// verify that all stubs were called
if err := httpmock.AllStubsCalled(); err != nil {
t.Errorf("Not all stubs were called: %s", err)
}
}
Advanced Example:
func TestFetchArticles(t *testing.T) {
httpmock.Activate(
WithAllowedHosts("localhost"),
)
defer httpmock.DeactivateAndReset()
// our database of articles
articles := make([]map[string]interface{}, 0)
// mock to list out the articles
httpmock.RegisterStubRequest(
httpmock.NewStubRequest(
"GET",
"https://api.mybiz.com/articles.json",
func(req *http.Request) (*http.Response, error) {
resp, err := httpmock.NewJsonResponse(200, articles)
if err != nil {
return httpmock.NewStringResponse(500, ""), nil
}
return resp
},
).WithHeader(
&http.Header{
"Api-Key": []string{"1234abcd"},
},
),
)
// mock to add a new article
httpmock.RegisterStubRequest(
httpmock.NewStubRequest(
"POST",
"https://api.mybiz.com/articles.json",
func(req *http.Request) (*http.Response, error) {
article := make(map[string]interface{})
if err := json.NewDecoder(req.Body).Decode(&article); err != nil {
return httpmock.NewStringResponse(400, ""), nil
}
articles = append(articles, article)
resp, err := httpmock.NewJsonResponse(200, article)
if err != nil {
return httpmock.NewStringResponse(500, ""), nil
}
return resp, nil
},
).WithHeader(
&http.Header{
"Api-Key": []string{"1234abcd"},
},
).WithBody(
bytes.NewBufferString(`{"title":"article"}`),
),
)
// do stuff that adds and checks articles
// verify that all stubs were called
if err := httpmock.AllStubsCalled(); err != nil {
t.Errorf("Not all stubs were called: %s", err)
}
}
*/
package httpmock