我有以下代碼:package mainimport ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time")type twitterResult struct { Results []struct { Text string `json:"text"` Ids string `json:"id_str"` Name string `json:"from_user_name"` Username string `json:"from_user"` UserId string `json:"from_user_id_str"` }}var ( twitterUrl = "http://search.twitter.com/search.json?q=%23UCL" pauseDuration = 5 * time.Second)func retrieveTweets(c chan<- *twitterResult) { for { resp, err := http.Get(twitterUrl) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) r := new(twitterResult) //or &twitterResult{} which returns *twitterResult err = json.Unmarshal(body, &r) if err != nil { log.Fatal(err) } c <- r time.Sleep(pauseDuration) }}func displayTweets(c chan *twitterResult) { tweets := <-c for _, v := range tweets.Results { fmt.Printf("%v:%v\n", v.Username, v.Text) }}func main() { c := make(chan *twitterResult) go retrieveTweets(c) for { displayTweets(c) }}我想為它編寫一些測試,但我不確定如何使用 httptest 包http://golang.org/pkg/net/http/httptest/希望得到一些指點我想出了這個(無恥地從 go OAuth https://code.google.com/p/goauth2/source/browse/oauth/oauth_test.go的測試中復制):var request = struct { path, query string // request contenttype, body string // response}{ path: "/search.json?", query: "q=%23Kenya", contenttype: "application/json", body: twitterResponse,}var ( twitterResponse = `{ 'results': [{'text':'hello','id_str':'34455w4','from_user_name':'bob','from_user_id_str':'345424'}]}`)func TestRetrieveTweets(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", request.contenttype) io.WriteString(w, request.body) }
3 回答
回首憶惘然
TA貢獻1847條經驗 獲得超11個贊
最初這個代碼片段是在 GitHub Gist 上找到的,但是在嘗試將這個概念應用于我的一個項目時,我意識到我必須顯著修改主要代碼,我決定使用 docker 和 curl 使用集成測試來測試這些調用。
- 3 回答
- 0 關注
- 367 瀏覽
添加回答
舉報
0/150
提交
取消
