How to test http calls in go

前端 未结 1 1466
野趣味
野趣味 2021-01-06 05:09

I have the following code:

// HTTPPost to post json messages to the specified url
func HTTPPost(message interface{}, url string) (*http.Response, error) {
           


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-06 05:17

    Take a look here:

    https://golang.org/pkg/net/http/httptest/#example_Server

    Basically, you can create a new "mock" http server using httptest.NewServer function.

    You can have your mock server return whatever response you need from the test, and you can also have your mock server store the request that your HTTPPost function made in order to assert over it.

    func TestYourHTTPPost(t *testing.T){
    
        ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, `response from the mock server goes here`)
            // you can also inspect the contents of r (the request) to assert over it
        }))
        defer ts.Close()
    
        mockServerURL = ts.URL
    
        message := "the message you want to test"
    
        resp, err := HTTPPost(message, mockServerURL)
    
        // assert over resp and err here
    }
    

    0 讨论(0)
提交回复
热议问题