Mastering Go HTTP Testing with httptest and gock: A Complete Guide

This article explains how to use Go's httptest package and the gock library to mock HTTP servers and external API calls, providing step‑by‑step code examples, test case structures, and installation instructions for effective backend unit testing.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Go HTTP Testing with httptest and gock: A Complete Guide

1. httptest

1.1 Preparation

Assume the business logic is an HTTP server handling a login request where users submit an email and password.

package main

import (
    "github.com/dlclark/regexp2"
    "github.com/gin-gonic/gin"
    "net/http"
)

type UserHandler struct {
    emailExp    *regexp.Regexp
    passwordExp *regexp.Regexp
}

func (u *UserHandler) RegisterRoutes(server *gin.Engine) {
    ug := server.Group("/user")
    ug.POST("/login", u.Login)
}

func NewUserHandler() *UserHandler {
    const (
        emailRegexPattern    = "^\\w+([-+. ]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"
        passwordRegexPattern = `^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$`
    )
    emailExp := regexp.MustCompile(emailRegexPattern, regexp.None)
    passwordExp := regexp.MustCompile(passwordRegexPattern, regexp.None)
    return &UserHandler{emailExp: emailExp, passwordExp: passwordExp}
}

type LoginRequest struct {
    Email string `json:"email"`
    Pwd   string `json:"pwd"`
}

func (u *UserHandler) Login(ctx *gin.Context) {
    var req LoginRequest
    if err := ctx.ShouldBindJSON(&req); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"msg": "参数不正确!"})
        return
    }
    if req.Email == "" || req.Pwd == "" {
        ctx.JSON(http.StatusBadRequest, gin.H{"msg": "邮箱或密码不能为空"})
        return
    }
    if ok, err := u.emailExp.MatchString(req.Email); err != nil || !ok {
        ctx.JSON(http.StatusBadRequest, gin.H{"msg": "邮箱格式不正确"})
        return
    }
    if ok, err := u.passwordExp.MatchString(req.Pwd); err != nil || !ok {
        ctx.JSON(http.StatusBadRequest, gin.H{"msg": "密码必须大于8位,包含数字、特殊字符"})
        return
    }
    if req.Email != "[email protected]" || req.Pwd != "hello#world123" {
        ctx.JSON(http.StatusBadRequest, gin.H{"msg": "邮箱或密码不匹配!"})
        return
    }
    ctx.JSON(http.StatusOK, gin.H{"msg": "登录成功!"})
}

func InitWebServer(userHandler *UserHandler) *gin.Engine {
    server := gin.Default()
    userHandler.RegisterRoutes(server)
    return server
}

func main() {
    uh := &UserHandler{}
    server := InitWebServer(uh)
    server.Run(":8080") // start on port 8080
}

1.2 Introduction

In web development, unit tests often need to mock HTTP requests and responses. The Go standard library net/http/httptest lets you create a test server, define request/response behavior, and simulate real network interactions.

1.3 Basic Usage

Typical steps: import net/http/httptest, create a httptest.Server, use httptest.NewRequest to craft a request, send it to the server, and verify the response.

package main

import (
    "bytes"
    "github.com/gin-gonic/gin"
    "github.com/stretchr/testify/assert"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestUserHandler_Login(t *testing.T) {
    testCases := []struct {
        name     string
        reqBody  string
        wantCode int
        wantBody string
    }{
        {"登录成功", `{"email":"[email protected]","pwd":"hello#world123"}`, http.StatusOK, `{"msg":"登录成功!"}`},
        {"参数不正确", `{"email":"[email protected]","pwd":"hello#world123",}`, http.StatusBadRequest, `{"msg":"参数不正确!"}`},
        {"邮箱或密码为空", `{"email":"","pwd":""}`, http.StatusBadRequest, `{"msg":"邮箱或密码不能为空"}`},
        {"邮箱格式不正确", `{"email":"invalidemail","pwd":"hello#world123"}`, http.StatusBadRequest, `{"msg":"邮箱格式不正确"}`},
        {"密码格式不正确", `{"email":"[email protected]","pwd":"invalidpassword"}`, http.StatusBadRequest, `{"msg":"密码必须大于8位,包含数字、特殊字符"}`},
        {"邮箱或密码不匹配", `{"email":"[email protected]","pwd":"hello#world123"}`, http.StatusBadRequest, `{"msg":"邮箱或密码不匹配!"}`},
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            server := gin.Default()
            h := NewUserHandler()
            h.RegisterRoutes(server)

            req, err := http.NewRequest(http.MethodPost, "/user/login", bytes.NewBuffer([]byte(tc.reqBody)))
            assert.NoError(t, err)
            req.Header.Set("Content-Type", "application/json")
            resp := httptest.NewRecorder()
            server.ServeHTTP(resp, req)

            assert.Equal(t, tc.wantCode, resp.Code)
            assert.JSONEq(t, tc.wantBody, resp.Body.String())
        })
    }
}
Test result screenshot
Test result screenshot

2. gock

2.1 Introduction

gock is a Go library that intercepts HTTP requests and provides mock responses, making it easy to test code that depends on external APIs.

2.2 Installation

go get -u github.com/h2non/gock
import "github.com/h2non/gock"

2.3 Basic Usage

Typical workflow: start an interceptor with gock.New, define matching rules with methods like Post and MatchType, set the desired response using JSON or NewText, then run your tests; gock will automatically intercept matching HTTP calls.

2.4 Example

2.4.1 Preparation

Suppose we have a function that calls an external API at http://your-api.com/post and processes the returned data.

// ReqParam API请求参数
type ReqParam struct {
    X int `json:"x"`
}

// Result API返回结果
type Result struct {
    Value int `json:"value"`
}

func GetResultByAPI(x, y int) int {
    p := &ReqParam{X: x}
    b, _ := json.Marshal(p)

    resp, err := http.Post("http://your-api.com/post", "application/json", bytes.NewBuffer(b))
    if err != nil {
        return -1
    }
    body, _ := ioutil.ReadAll(resp.Body)
    var ret Result
    if err := json.Unmarshal(body, &ret); err != nil {
        return -1
    }
    return ret.Value + y
}

2.4.2 Test Cases

package gock_demo

import (
    "testing"
    "github.com/stretchr/testify/assert"
    "gopkg.in/h2non/gock.v1"
)

func TestGetResultByAPI(t *testing.T) {
    defer gock.Off()

    // mock x=1 returns value 100
    gock.New("http://your-api.com").
        Post("/post").
        MatchType("json").
        JSON(map[string]int{"x": 1}).
        Reply(200).
        JSON(map[string]int{"value": 100})

    res := GetResultByAPI(1, 1)
    assert.Equal(t, 101, res)

    // mock x=2 returns value 200
    gock.New("http://your-api.com").
        Post("/post").
        MatchType("json").
        JSON(map[string]int{"x": 2}).
        Reply(200).
        JSON(map[string]int{"value": 200})

    res = GetResultByAPI(2, 2)
    assert.Equal(t, 202, res)

    assert.True(t, gock.IsDone())
}
Illustrative image
Illustrative image

Sharing knowledge brings joy.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendGounit testingMockingAPI testinghttptestgock
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.