unit-testing - 在 Go 中测试依赖于动态 URL 的处理函数

标签 unit-testing http go

我一直在寻找答案,但找不到。我的问题是,是否可以测试依赖于动态 URL token 的处理函数?

例如,假设我的处理程序函数需要来自动态生成的 URL 的 token (我不知道 token 是如何生成的,除了 URL 参数之外我也无法访问它)。我的 URL 总是看起来像这样:www.example.com/?token=randomtokenhere

func TokenProcessing(w http.ResponseWriter, r *http.Request) {
     token := r.URL.Query().Get("token") // dynamically generated from parsed URL 

      // code to do something with said token

}

是否可以在不访问 token 创建方式的情况下以某种方式对该处理程序函数进行单元测试?

最佳答案

您可以填充 http.Request 的查询参数,然后使用 httptest.ResponseRecorder 测试处理程序

例如

package main

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

// In this test file to keep the SO example concise
func TokenProcessing(w http.ResponseWriter, r *http.Request) {
    token := r.URL.Query().Get("token") // dynamically generated from parsed URL
    // code to do something with said token
    log.Println(token)
}

func TestTokenProcessing(t *testing.T) {
    rr := httptest.NewRecorder()
    r, err := http.NewRequest("GET", "http://golang.org/", nil)
    if err != nil {
        t.Fatal(err)
    }

    // Generate suitable values here - e.g. call your generateToken() func
    r.URL.Query().Add("token", "someval")

    handler := http.HandlerFunc(TokenProcessing)
    handler.ServeHTTP(rr, r)

    if code := rr.Code; code != http.StatusOK {
        t.Fatalf("handler did not return correct status: want %v got %v",
            http.StatusOK, code)
    }

    // Test the rest of the response - i.e. sets a header, etc.
}

关于unit-testing - 在 Go 中测试依赖于动态 URL 的处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888744/

相关文章:

c++ - 如何嵌入实时单元测试函数的主体作为 Doxygen 的示例用法?

c# - 使用异步任务<ActionResult>对 ASP.NET MVC 5 Controller 进行单元测试

c++ - 如何进行单元测试(使用 CMake 和 GTest)来了解测试数据的文件夹在哪里?

session - Gorilla session 文件系统存储找不到 session 文件

c# - 单元测试自动映射器

javascript - Angular js - 从方法外部返回和 console.log $http 响应

java - 如何增加 Tomcat Java header 大小限制

python - 使用 python-requests 压缩请求体?

go - 无法无限期地写入一个 goroutine 并从另一个 goroutine 中读取

c - 为什么这个简单的循环在 Go 中比在 C 中更快?