测试处理程序功能依赖于Go中的动态URL

时间:2015-08-08 01:30:51

标签: unit-testing http go

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

例如,假设我的处理函数需要动态生成的URL中的标记(我不知道如何生成标记,除了URL参数之外我也无法访问它)。我的网址总是如下所示:www.example.com/?token=randomtokenhere

//first you need to create an array of employee record IDs
var employeeRecordIds = [CKRecordID]()
for employeeReference in companyRecord["Employees"] as! [CKReference] {
    employeeRecordIds.append(employeeReference.recordID)
}
//now you can fetch those employees
var fetchOperation = CKFetchRecordsOperation(recordIDs: employeeRecordIds)
fetchOperation.fetchRecordsCompletionBlock = {
    records, error in
    if error != nil {
        print("\(error!)")
    } else {
        for (recordId, record) in records {
            print("\(record)")
        }
    }
}
CKContainer.defaultContainer().publicCloudDatabase.addOperation(fetchOperation)

是否可以以某种方式单元测试此处理程序函数而无需访问如何创建令牌?

2 个答案:

答案 0 :(得分:2)

您可以填充http.Request的查询参数,然后使用httptest.ResponseRecorder

测试处理程序

e.g。

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.
}

答案 1 :(得分:0)

我能想到的最简单的事情是创建一个辅助函数,它将所有参数作为处理程序,并另外将标记作为参数。然后你可以单独测试该功能。如下所示:

func TokenProcessing(w http.ResponseWriter, r *http.Request) {
    token := r.URL.Query().Get("token")
    tokenProcessingHelper(w, r, token)
}

// unit test me!
func tokenProcessingHelper(w http.ResponseWriter, r *http.Request, token string) {
    ...
}