forked from goinaction/code
-
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.
Moved tests into the handlers package
- Loading branch information
1 parent
b5198a5
commit 57f2d4a
Showing
3 changed files
with
67 additions
and
8 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
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,63 @@ | ||
// Sample test to show how to test the execution of an | ||
// internal endpoint. | ||
package handlers_test | ||
|
||
import ( | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/goinaction/code/chapter9/listing04/handlers" | ||
) | ||
|
||
const checkMark = "\u2713" | ||
const ballotX = "\u2717" | ||
|
||
func init() { | ||
handlers.Routes() | ||
} | ||
|
||
// TestSendJSON testing the sendjson internal endpoint. | ||
func TestSendJSON(t *testing.T) { | ||
t.Log("Given the need to test the SendJSON endpoint.") | ||
{ | ||
r, err := http.NewRequest("GET", "/sendjson", nil) | ||
if err != nil { | ||
t.Fatal("\tShould be able to create a request.", | ||
ballotX, err) | ||
} | ||
t.Log("\tShould be able to create a request.", | ||
checkMark) | ||
|
||
w := httptest.NewRecorder() | ||
http.DefaultServeMux.ServeHTTP(w, r) | ||
|
||
if w.Code != 200 { | ||
t.Fatal("\tShould receive \"200\"", ballotX, w.Code) | ||
} | ||
t.Log("\tShould receive \"200\"", checkMark) | ||
|
||
u := struct { | ||
Name string | ||
Email string | ||
}{} | ||
|
||
if err := json.NewDecoder(w.Body).Decode(&u); err != nil { | ||
t.Fatal("\tShould decode the response.", ballotX) | ||
} | ||
t.Log("\tShould decode the response.", checkMark) | ||
|
||
if u.Name == "Bill" { | ||
t.Log("\tShould have a Name.", checkMark) | ||
} else { | ||
t.Error("\tShould have a Name.", ballotX, u.Name) | ||
} | ||
|
||
if u.Email == "[email protected]" { | ||
t.Log("\tShould have an Email.", checkMark) | ||
} else { | ||
t.Error("\tShould have an for Email.", ballotX, u.Email) | ||
} | ||
} | ||
} |