Mocking proto.Message in Go

huangapple go评论70阅读模式
英文:

Mocking proto.Message in Go

问题

我编写了一个函数,它接受一个proto.Message对象的列表。根据文档,似乎proto.Message包装了protoreflect.ProtoMessage,其中包含一个名为ProtoReflect() Message的函数。根据文档Message实现了一些其他函数,这些函数返回protoreflect包引用的类型。

看起来创建一个模拟的proto.Message对象可能需要更多的工作,而且可能不值得,但我不想为了单元测试而经历创建protobuf文件、编译和引用的整个过程。

是否有其他方法可以创建一个模拟的proto.Message对象?

英文:

I wrote a function that takes a list of proto.Message objects. Looking at the documentation, it seems like proto.Message wraps protoreflect.ProtoMessage which contains a single function, ProtoReflect() Message. Looking at the documentation for Message, it implements a number of other functions that return types referenced by the protoreflect package.

It seems that attempting to create a mock proto.Message would be a lot more work that it's worth but I don't want to go through the whole process of creating a protobuf file, compiling it and referencing it just for unit testing.

Is there another way I can create a mock proto.Message object?

答案1

得分: 0

在进一步调查后,我决定最好的做法是创建一个实际的protobuf消息:

syntax = "proto3";
package my.package;

option go_package = "path/to/my/package"; // golang

message TestRecord {
    string key = 1;
    string value = 2;
}

然后将其编译为Golang文件,并根据我的需求进行修改:

$ protoc --go_out=./gopb/ --go_opt=paths=source_relative *.proto

一旦测试文件被创建,我可以删除它或将其保存为记录。

英文:

After looking into this further, I decided that the best thing to do would be to create an actual protobuf message:

syntax = "proto3";
package my.package;

option go_package = "path/to/my/package"; // golang

message TestRecord {
    string key = 1;
    string value = 2;
}

and compile it into a Golang file and then modify it for my own purposes:

$ protoc --go_out=./gopb/ --go_opt=paths=source_relative *.proto

Once the test file has been created, I can delete it or save it as a record.

huangapple
  • 本文由 发表于 2022年5月19日 14:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/72299578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定