-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_test.go
62 lines (48 loc) · 1.06 KB
/
mock_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
package httpmock_test
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"go.nhat.io/httpmock"
)
type TestingT struct {
strings.Builder
clean func()
}
func (t *TestingT) Errorf(format string, args ...any) {
_, _ = fmt.Fprintf(t, format, args...)
}
func (t *TestingT) FailNow() {
panic("failed")
}
func (t *TestingT) Cleanup(clean func()) {
t.clean = clean
}
func T() *TestingT {
return &TestingT{
clean: func() {},
}
}
func TestMock(t *testing.T) {
t.Parallel()
s := httpmock.New(func(s *Server) {
s.ExpectPost("/create").
WithHeader("Authorization", "Bearer token").
WithBody(`{"foo":"bar"}`).
ReturnCode(http.StatusCreated).
Return(`{"id":1,"foo":"bar"}`)
})(t)
defer s.Close()
code, _, body, _ := httpmock.DoRequest(t,
http.MethodPost,
s.URL()+"/create",
map[string]string{"Authorization": "Bearer token"},
[]byte(`{"foo":"bar"}`),
)
expectedCode := http.StatusCreated
expectedBody := []byte(`{"id":1,"foo":"bar"}`)
assert.Equal(t, expectedCode, code)
assert.Equal(t, expectedBody, body)
}