Skip to content

Commit

Permalink
feat: stub with bytes (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
le-yams authored Oct 15, 2024
1 parent d6aa6bf commit aae13fd
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
18 changes: 11 additions & 7 deletions stubs.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@ func (stub *StubBuilder) WithStatusCode(statusCode int) *APIMock {
}

func (stub *StubBuilder) WithJSON(statusCode int, content interface{}) *APIMock {
body, err := json.Marshal(content)
if err != nil {
log.Fatal(err)
}

return stub.WithBody(statusCode, body, "application/json")
}

func (stub *StubBuilder) WithBody(statusCode int, body []byte, contentType string) *APIMock {
return stub.With(func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Add("Content-Type", "application/json")
writer.Header().Add("Content-Type", contentType)
writer.WriteHeader(statusCode)

bytes, err := json.Marshal(content)
if err != nil {
log.Fatal(err)
}
_, err = writer.Write(bytes)
_, err := writer.Write(body)
if err != nil {
log.Fatal(err)
}
Expand Down
32 changes: 32 additions & 0 deletions stubs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,42 @@ func TestApiStubbedEndpointWithJson(t *testing.T) {
// Assert
testState.assertDidNotFailed()

e.GET("/endpoint").
Expect().
Header("Content-Type").IsEqual("application/json")

responseObject := e.GET("/endpoint").
Expect().
Status(http.StatusOK).
JSON().Object()

responseObject.Value("value").IsEqual("Hello")
}

func TestApiStubbedEndpointWithBody(t *testing.T) {
t.Parallel()
// Arrange
testState := NewTestingMock(t)
mockedAPI := API(testState)
defer func() { mockedAPI.Close() }()
body := []byte("Hello!")

mockedAPI.
Stub(http.MethodGet, "/endpoint").
WithBody(http.StatusOK, body, "text/plain")

// Act
e := httpexpect.Default(t, mockedAPI.GetURL().String())

// Assert
testState.assertDidNotFailed()

e.GET("/endpoint").
Expect().
Header("Content-Type").IsEqual("text/plain")

e.GET("/endpoint").
Expect().
Status(http.StatusOK).
Body().IsEqual("Hello!")
}

0 comments on commit aae13fd

Please sign in to comment.