为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 go 中测试 pubsub 消息确认?

如何在 go 中测试 pubsub 消息确认?

Go
侃侃尔雅 2022-06-06 14:53:36
如何编写一个单元测试来验证消息是否真的被确认了?我想模拟 pubsub 消息并验证它Ack是否被调用但无法实现。func processMessage(ctx context.Context, msg *pubsub.Message) {    log.Printf("Processing message, data: %s", msg.Data)    msg.Ack()}
查看完整描述

2 回答

?
幕布斯7119047

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()

}


查看完整回答
反对 回复 2022-06-06
?
largeQ

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被调用。您可以为此使用作证/模拟。


查看完整回答
反对 回复 2022-06-06
  • 2 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号