-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
56 lines (47 loc) · 1.26 KB
/
mock.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
package httpmock
import (
"github.com/stretchr/testify/assert"
"go.nhat.io/httpmock/test"
)
// Mocker is a function that applies expectations to the mocked server.
type Mocker func(t test.T) *Server
// MockServer creates a mocked server.
func MockServer(mocks ...func(s *Server)) *Server {
s := NewServer()
for _, m := range mocks {
m(s)
}
return s
}
// New creates a mocker server with expectations and assures that ExpectationsWereMet() is called.
//
// s := httpmock.New(func(s *Server) {
// s.ExpectPost("/create").
// WithHeader("Authorization", "Bearer token").
// WithBody(`{"foo":"bar"}`).
// ReturnCode(httpmock.StatusCreated).
// Return(`{"id":1,"foo":"bar"}`)
// })(t)
//
// code, _, body, _ := httpmock.DoRequest(t,
// httpmock.MethodPost,
// s.URL()+"/create",
// map[string]string{"Authorization": "Bearer token"},
// []byte(`{"foo":"bar"}`),
// )
//
// expectedCode := httpmock.StatusCreated
// expectedBody := []byte(`{"id":1,"foo":"bar"}`)
//
// assert.Equal(t, expectedCode, code)
// assert.Equal(t, expectedBody, body)
func New(mocks ...func(s *Server)) Mocker {
return func(t test.T) *Server {
s := MockServer(mocks...).WithTest(t)
t.Cleanup(func() {
assert.NoError(t, s.ExpectationsWereMet())
s.Close()
})
return s
}
}