Skip to content

Instantly share code, notes, and snippets.

Created July 4, 2015 08:24
Show Gist options
  • Save anonymous/3b2085f064d852a23787 to your computer and use it in GitHub Desktop.
Save anonymous/3b2085f064d852a23787 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"net/http/httptest"
"testing"
"strings"
"addressbook/contact"
"io/ioutil"
)
func TestAddContacts(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(addressBookHandler))
defer ts.Close()
clen := len(contacts)
resp, _ := http.Post(ts.URL+"/contacts", "application/json", strings.NewReader(`{
"name": "Hello",
"tel": "00112233",
"email": "h@mail.com"
}`))
if resp.StatusCode != http.StatusOK {
t.Error("Expected status code is 200 OK")
}
if len(contacts) != clen + 1 {
t.Error("Expected contacts have a new data")
}
c := contacts[0]
if (c.Name != "Hello") {
t.Error("Expected name should match with request one, but appeared", c.Name)
}
if (c.Tel != "00112233") {
t.Error("Expected telephone number should match with request one, but appeared", c.Tel)
}
if (c.Email != "h@mail.com") {
t.Error("Expected email should match with request one, but appeared", c.Email)
}
}
func TestFindContacts(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(addressBookHandler))
defer ts.Close()
contacts = []contact.Contact{
contact.Contact{
Name: "mhee",
Tel: "000111222",
Email: "h@mail.com",
},
}
getResp, _ := http.Get(ts.URL+"/contacts?name=mhee")
if getResp.StatusCode != http.StatusOK {
t.Error("Expected status code is 200 OK")
}
if getResp.ContentLength < 1 {
t.Error("Expected contact named mhee should be available")
}
b, _ := ioutil.ReadAll(getResp.Body)
if string(b) != `{"name":"mhee","tel":"000111222","email":"h@mail.com"}` + "\n" {
t.Error("Expected contact named mhee and data within app should be the same")
}
noResultResp, _ := http.Get(ts.URL+"/contacts?name=mhe")
if noResultResp.StatusCode != http.StatusOK {
t.Error("Expected status code is 200 OK")
}
if (noResultResp.ContentLength > 0) {
t.Error("Expeced contact named mhe should not found")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment