Home >Backend Development >Golang >How to Effectively Test HTTP Calls in Go using `httptest`?

How to Effectively Test HTTP Calls in Go using `httptest`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 08:15:15564browse

How to Effectively Test HTTP Calls in Go using `httptest`?

How to Test HTTP Calls in Go Using httptest

Introduction

HTTP testing in Go can be facilitated using the httptest package. This article explores how to leverage httptest for response and server testing, including a detailed example of server testing.

Types of Tests

httptest provides two categories of tests:

  • Response tests: Verifies the HTTP response received from a request.
  • Server tests: Emulates a server to test HTTP interactions with the application under test.

Response Test

In response testing, a Recorder object captures the response and its contents. The following code snippet demonstrates a response test:

resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/3D/header/?", nil)

http.DefaultServeMux.ServeHTTP(resp, req)

Server Test

For server testing, httptest simulates a server and provides a URL that can be used:

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, `{"fake twitter json string"}`)
}))

In this example, a server that responds with predefined JSON data is created. The URL of this server can then be used in the application under test.

Example: Testing HTTP Calls in retrieveTweets

To test the retrieveTweets function:

func TestIt(t *testing.T){
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, `{"fake twitter json string"}`)
    }))
    defer ts.Close()

    twitterUrl = ts.URL
    c := make(chan *twitterResult)
    go retrieveTweets(c)

    tweet := <-c
    if tweet != expected1 {
        t.Fail()
    }
    tweet = <-c
    if tweet != expected2 {
        t.Fail()
    }
}

By mocking the server, we can verify the results received by the retrieveTweets function.

The above is the detailed content of How to Effectively Test HTTP Calls in Go using `httptest`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn