-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* test: http helpers * test: add test for respond with json through generic interface * test: adding test for error response
- Loading branch information
1 parent
1c6fdac
commit 3a462b2
Showing
2 changed files
with
56 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package main | ||
|
||
import ( | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
) | ||
|
||
func TestRespondWithJSON(t *testing.T) { | ||
t.Run("test respond with json with generic interface", func(t *testing.T) { | ||
response := httptest.NewRecorder() | ||
|
||
type FooStruct struct { | ||
Foo string `json:"foo"` | ||
} | ||
|
||
testStruct := FooStruct{ | ||
Foo: "bar", | ||
} | ||
|
||
respondWithJSON(response, http.StatusOK, testStruct) | ||
|
||
wantStruct := FooStruct{} | ||
|
||
err := json.NewDecoder(response.Body).Decode(&wantStruct) | ||
|
||
if err != nil { | ||
t.Errorf("could not parse result as expected") | ||
} | ||
|
||
if testStruct != wantStruct { | ||
t.Errorf("failed to respond with arbitrary interface got %q want %q", testStruct, wantStruct) | ||
} | ||
}) | ||
} | ||
|
||
func TestRespondWithError(t *testing.T) { | ||
t.Run("test respond with error with generic error", func(t *testing.T) { | ||
response := httptest.NewRecorder() | ||
|
||
respondWithError(response, http.StatusInternalServerError, "stuff is broken") | ||
|
||
wantStruct := errorResponse{} | ||
|
||
err := json.NewDecoder(response.Body).Decode(&wantStruct) | ||
|
||
if err != nil { | ||
t.Errorf("could not parse result as expected") | ||
} | ||
|
||
if wantStruct.Error != "stuff is broken" { | ||
t.Errorf("failed to respond with a generic error") | ||
} | ||
}) | ||
} |