-
-
Save aimakun/87e41d77df1805a07215 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"addressbook/contact" | |
"io/ioutil" | |
"net/http" | |
"net/http/httptest" | |
"strings" | |
"testing" | |
) | |
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.StatusNotFound { | |
t.Error("Expected status code is 404 Not Found") | |
} | |
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