亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 GoLang 測試用例中發送 google.protobuf.Struct 數據?

如何在 GoLang 測試用例中發送 google.protobuf.Struct 數據?

Go
一只斗牛犬 2022-06-06 15:15:11
我正在使用 GRPC/proto-buffers 在 GoLang 中編寫我的第一個 API 端點。我對 GoLang 比較陌生。以下是我為測試用例編寫的文件package my_packageimport (    "context"    "testing"    "github.com/stretchr/testify/require"    "google.golang.org/protobuf/types/known/structpb"    "github.com/MyTeam/myproject/cmd/eventstream/setup"    v1handler "github.com/MyTeam/myproject/internal/handlers/myproject/v1"    v1interface "github.com/MyTeam/myproject/proto/.gen/go/myteam/myproject/v1")func TestEndpoint(t *testing.T) {    conf := &setup.Config{}    // Initialize our API handlers    myhandler := v1handler.New(&v1handler.Config{})    t.Run("Success", func(t *testing.T) {        res, err := myhandler.Endpoint(context.Background(), &v1interface.EndpointRequest{            Data: &structpb.Struct{},        })        require.Nil(t, err)        // Assert we got what we want.        require.Equal(t, "Ok", res.Text)    })}這是在上面包含的文件EndpointRequest中定義對象的方式:v1.go// An v1 interface Endpoint Request object.message EndpointRequest {  // data can be a complex object.  google.protobuf.Struct data = 1;}這似乎有效。但現在,我想做一些稍微不同的事情。在我的測試用例中data,我想發送一個帶有鍵/值對的地圖/字典,而不是發送一個空對象A: "B", C: "D"。我該怎么做?如果我替換Data: &structpb.Struct{}為Data: &structpb.Struct{A: "B", C: "D"},我會得到編譯器錯誤:invalid field name "A" in struct initializerinvalid field name "C" in struct initializer 
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

您初始化的Data方式意味著您期待以下內容:


type Struct struct {

    A string

    C string

}

但是,structpb.Struct定義如下:


type Struct struct {   

    // Unordered map of dynamically typed values.

    Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`

    // contains filtered or unexported fields

}

顯然那里有點不匹配。您需要初始化Fields結構的映射并使用正確的方式設置Value字段。與您顯示的代碼等效的是:


Data: &structpb.Struct{

    Fields: map[string]*structpb.Value{

        "A": &structpb.Value{

            Kind: &structpb.Value_StringValue{

                StringValue: "B",

            },

        },

        "C": &structpb.Value{

            Kind: &structpb.Value_StringValue{

                StringValue: "D",

            },

        },

    },

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 504 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號