Golang HTTP REST模拟

I writing a client that connects to a server with REST endpoints. The client needs to make a chain of 11 different requests to complete an action (it's a rococo backup system).

I'm writing my client in Go and I also want to write my mocks/tests in Go. What I'm unclear about is how a test called func TestMain would call into the client's func main(), to test completion of the chain of 11 requests.

My client's binary would be run from the shell in the following way:

$ client_id=12345 region=apac3 backup

How would I call func main() from the tests, with environment variables set? Or is there another approach? (I'm comfortable writing tests, so that's not the issue)

I'm looking at the Advanced Example in jarcoal/httpmock (but I could use another library). At the end the example says // do stuff that adds and checks articles, is that where I would call main()?

I've pasted the Advanced Example below, for future reference.


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
}

Writing this out helped me answer my own question.

main() would read in environment variables and then call a function like doBackup(client_id, region). My test would mock the endpoints and then call doBackup(client_id, region).