测试修改请求的golang中间件

标签 testing go middleware

我有一些中间件可以将带有请求 ID 的上下文添加到请求中。

func AddContextWithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    var ctx context.Context
    ctx = NewContextWithRequestID(ctx, r)
    next.ServeHTTP(w, r.WithContext(ctx))
})}

如何为此编写测试?

最佳答案

要对此进行测试,您需要运行传递请求的处理程序,并使用自定义 next 处理程序来检查请求是否确实已修改。

您可以按如下方式创建该处理程序:

(我假设您的 NewContextWithRequestID 向具有“1234”值的请求添加了一个“reqId”键,您当然应该根据需要修改断言)

// create a handler to use as "next" which will verify the request
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    val := r.Context().Value("reqId")
    if val == nil {
        t.Error("reqId not present")
    }
    valStr, ok := val.(string)
    if !ok {
        t.Error("not string")
    }
    if valStr != "1234" {
        t.Error("wrong reqId")
    }
})

然后您可以将该处理程序用作您的下一个:

// create the handler to test, using our custom "next" handler
handlerToTest := AddContextWithRequestID(nextHandler)

然后调用该处理程序:

// create a mock request to use
req := httptest.NewRequest("GET", "http://testing", nil)
// call the handler using a mock response recorder (we'll not use that anyway)
handlerToTest.ServeHTTP(httptest.NewRecorder(), req)

将所有内容放在一起作为一个工作测试,就是下面的代码。

注意:我修复了您原来的“AddContextWithRequestID”中的一个小错误,因为当您只是在没有初始化的情况下声明它。

import (
    "net/http"
    "context"
    "testing"
    "net/http/httptest"
)

func NewContextWithRequestID(ctx context.Context, r *http.Request) context.Context {
    return context.WithValue(ctx, "reqId", "1234")
}

func AddContextWithRequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var ctx = context.Background()
        ctx = NewContextWithRequestID(ctx, r)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func TestIt(t *testing.T) {

    // create a handler to use as "next" which will verify the request
    nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        val := r.Context().Value("reqId")
        if val == nil {
            t.Error("reqId not present")
        }
        valStr, ok := val.(string)
        if !ok {
            t.Error("not string")
        }
        if valStr != "1234" {
            t.Error("wrong reqId")
        }
    })

    // create the handler to test, using our custom "next" handler
    handlerToTest := AddContextWithRequestID(nextHandler)

    // create a mock request to use
    req := httptest.NewRequest("GET", "http://testing", nil)

    // call the handler using a mock response recorder (we'll not use that anyway)
    handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
}

关于测试修改请求的golang中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201056/

相关文章:

go - 从 Slice 嵌套函数

testing - 如何在测试失败时使用 PHPUnit 和 Selenium2 进行截图?

testing - QTP_errObject CaptureBitmap

unit-testing - 干净地卸载 Rspec 并在 Rails 3.x 中使用 vanilla Unit::Test

json - golang中严格的json解析器

go - 如何在 Windows 上从 Golang 执行 netsh 命令

jQuery 移动 : Can I "uninitialize" the page?

mysql - 如何从 GO 在 mysql 中创建触发器。似乎不支持使用 DELIMITER

node.js - nodeJs/Express 处理丢失的静态文件

ruby - @app.call(env) 到底做了什么?