如何将struct转换为[]byte类型?

问题描述 投票:0回答:1

我阅读了这篇文章,使用

httptest
来模拟出站HTTP请求,但是包含我想要模拟的请求的代码行返回一个名为gophercloud.ProviderClient的结构

func Authenticate() (*gophercloud.ProviderClient, error) {
    provider, err := openstack.AuthenticatedClient(authOpts)
}

我为这行代码编写的测试函数是这样的:

func TestGetAuthClient(t *testing.T) {
    //Fixed value that should be returned 
    mockProvider := &gophercloud.ProviderClient{}

    //Create server object to intercept request
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "https://endpoint-to-get-authenticated-client/api" {
            t.Errorf("Expected to request '/fixedvalue', got: %s", r.URL.Path)
        }

        w.WriteHeader(http.StatusOK)
        w.Write([]byte(mockProvider)) // Error here
    }))

    defer server.Close()

    client, err := Authenticate()
    if err != nil {
        t.Errorf("Provider client failed")
    }
    if client != nil {
        t.Errorf("Expected 'fixed', got %v", pc)
    }
}

但是尝试将固定测试值写入

w.Write([]byte(mockProvider))
将会抛出
cannot convert mockProvider (variable of type *gophercloud.ProviderClient) to type []byte
。不幸的是,我并没有真正理解阅读
w.Write
的文档。

unit-testing go
1个回答
0
投票

将 struct 转换为 json 怎么样?

byteMockProvider, _ := json.Marshal(mockProvider)
w.Write(byteMockProvider)
© www.soinside.com 2019 - 2024. All rights reserved.