2 回答
TA贡献1794条经验 获得超8个赞
您可以创建一个包装消息的接口和一个包装接收函数类型的函数。
// message interface to pass to our message handler
type Message interface {
GetData() []byte
Ack()
}
// real message for pubsub messages
type msg struct {
m *pubsub.Message
}
// returns real message data
func (i *msg) GetData() {
return i.m.Data
}
// acks the real pubsub message
func (i *msg) Ack() {
i.m.Ack()
}
// test message can be passed to the handleMessage function
type testMsg struct {
d []byte
}
// returns the test data
func (t *testMsg) GetData() []byte {
return d
}
// does nothing so we can test our handleMessage function
func (t *testMsg) Ack() {}
func main() {
client, err := pubsub.NewClient(context.Background(), "projectID")
if err != nil {
log.Fatal(err)
}
sub := client.Subscription("pubsub-sub")
sub.Receive(ctx, createHandler())
}
// creates the handler, allows us to pass our interface to the message handler
func createHandler() func(ctx context.Context, m *pubsub.Message) {
// returns the correct function type but uses our message interface
return func(ctx context.Context, m *pubsub.Message) {
handleMessage(ctx, &msg{m})
}
}
// could pass msg or testMsg here because both meet the interface Message
func handleMessage(ctx context.Context, m Message) {
log.Println(m.GetData())
m.Ack()
}
TA贡献2039条经验 获得超8个赞
您可以通过使用接口和模拟来做到这一点,如下所示。
// Create an interface that'll be implemented by *pubsub.Message
type message interface{
Ack()
}
// Accept the interface instead of the concrete struct
func processMessage(ctx context.Context, msg message) {
log.Printf("Processing message, data: %s", msg.Data)
msg.Ack()
}
现在,在测试文件中,创建一个模拟消息并确认是否Ack被调用。您可以为此使用作证/模拟。
- 2 回答
- 0 关注
- 181 浏览
添加回答
举报
