unit-testing - 如何在 golang 中注入(inject)一个 url 到 httptest.server?

标签 unit-testing go gomock

对于句子

resp, err := client.Get(fmt.Sprintf("https://www.xxxxx/day?time=%s", time))

如果我想在单元测试中模拟对此 client.Get() 的响应,我应该使用 httptest.server,但是如何将 url ( https://www.xxxxx/day?time=%s) 绑定(bind)到 httptest.server 的 url?这样当我调用 client.Get() 时它可以返回我之前设置的响应。 出于某种原因,我不能在这里模拟客户。

最佳答案

通常不会。您从服务器获取基本 URL 并将其提供给客户端:

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "testing"
    "time"
)

func TestClient(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Verify request, send mock response, etc.
    }))

    defer server.Close()

    var client *http.Client
    var time time.Time

    baseURL := server.URL // Something like "http://127.0.0.1:53791"
    resp, err := client.Get(fmt.Sprintf(baseURL+"/day?time=%s", time))
    if err != nil {
            t.Fatal(err)
    }

    // Verify response body if applicable

    resp.Body.Close()
}

关于unit-testing - 如何在 golang 中注入(inject)一个 url 到 httptest.server?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944063/

相关文章:

Golang : how to mock . ..interface{} arguents 使用 gomock

go - 在测试中添加gomock测试到项目会产生“构建约束排除所有Go文件”

android - 如何向代码库追溯添加测试?

c# - 如何导出 C# 单元测试的结果?

go - 加朗 : type interface {} does not support indexing

pointers - 返回类型与 struct golang 相同

go - 打印时如何取消引用字段?

java - 创建 nunit 测试而不使用 api 导出它们

angularjs - AngularJS 上的单元测试 $scope.$

go - 由于未接来电而导致测试中止