2017-10-03 14 views
1

RESTエンドポイントを持つサーバーに接続するクライアントを作成しました。クライアントは、アクションを完了するために11種類の要求の連鎖を作成する必要があります(バックアップシステムはrococoです)。Golang HTTP REST mocking

私はGoに自分のクライアントを書いています。私はGoに自分の模擬テストを書いています。私が不明な点は、func TestMainというテストがクライアントのfunc main()を呼び出して11の要求のチェーンの完了をテストする方法です。環境変数を設定して、私は、テストからfunc main()呼び出す方法

$ client_id=12345 region=apac3 backup

私のクライアントのバイナリは、次のようにシェルから実行するのでしょうか?それとも別のアプローチがありますか? (私はcomfortable writing testsだから問題ではない)

先進的な例をjarcoal/httpmock(私は別のライブラリを使うこともできます)で見ています。最後の例では// do stuff that adds and checks articlesと書かれていますが、私はmain()と呼んでいますか?

今後の参考として、以下のアドバンスドサンプルを貼り付けました。このアウトを書く


func TestFetchArticles(t *testing.T) { 
    httpmock.Activate() 
    defer httpmock.DeactivateAndReset() 

    // our database of articles 
    articles := make([]map[string]interface{}, 0) 

    // mock to list out the articles 
    httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json", 
     func(req *http.Request) (*http.Response, error) { 
      resp, err := httpmock.NewJsonResponse(200, articles) 
      if err != nil { 
       return httpmock.NewStringResponse(500, ""), nil 
      } 
      return resp, nil 
     }, 
    ) 

    // mock to add a new article 
    httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json", 
     func(req *http.Request) (*http.Response, error) { 
      article := make(map[string]interface{}) 
      if err := json.NewDecoder(req.Body).Decode(&article); err != nil { 
       return httpmock.NewStringResponse(400, ""), nil 
      } 

      articles = append(articles, article) 

      resp, err := httpmock.NewJsonResponse(200, article) 
      if err != nil { 
       return httpmock.NewStringResponse(500, ""), nil 
      } 
      return resp, nil 
     }, 
    ) 

    // do stuff that adds and checks articles 
} 

答えて

1

私は自分の質問に答える助けました。

main()は、環境変数を読み込み、doBackup(client_id, region)のような関数を呼び出します。私のテストではエンドポイントを模擬してdoBackup(client_id, region)と呼ぶでしょう。