Google-cloud-go: pubsub: mock pubsub client

Created on 26 Apr 2019  路  3Comments  路  Source: googleapis/google-cloud-go

I am using google pubsub right now, but for unit testing i can't use it since i'm not put the config when test.
So, can someone help me to mock the pubsub client ?

pubsub question

Most helpful comment

Thank you for this request @deelienardy and welcome to the Google apis Go cloud project!

So the constructor for a client is https://godoc.org/cloud.google.com/go/pubsub#NewClient
and it takes in options

func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (c *Client, err error)

where opts is of type ...option.ClientOption https://godoc.org/google.golang.org/api/option#ClientOption

and some of the options that'll perhaps help with this task are:

There are a couple of options that you can use when connecting to your unit test mock server.

The simplest to use for mocking is WithGRPCConn

conn, err := grpc.Dial(myMockServerAddress, grpc.WithInsecure())
if err != nil {
      // TODO: Handle the error
}

// Now create the pubsub client with the grpc conn
client, err := pubsub.NewClient(ctx, projectID, option.WithGRPCConn(conn))

Hope this helps.

All 3 comments

Thank you for this request @deelienardy and welcome to the Google apis Go cloud project!

So the constructor for a client is https://godoc.org/cloud.google.com/go/pubsub#NewClient
and it takes in options

func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (c *Client, err error)

where opts is of type ...option.ClientOption https://godoc.org/google.golang.org/api/option#ClientOption

and some of the options that'll perhaps help with this task are:

There are a couple of options that you can use when connecting to your unit test mock server.

The simplest to use for mocking is WithGRPCConn

conn, err := grpc.Dial(myMockServerAddress, grpc.WithInsecure())
if err != nil {
      // TODO: Handle the error
}

// Now create the pubsub client with the grpc conn
client, err := pubsub.NewClient(ctx, projectID, option.WithGRPCConn(conn))

Hope this helps.

@deelienardy Besides passing a custom mock through WithGRPCConn, as @odeke-em suggested, you can also use our in-memory fake https://godoc.org/cloud.google.com/go/pubsub/pstest.

Furthermore, we have https://github.com/googleapis/google-cloud-go-testing which provides mocking interfaces, but unfortunately we haven't added pubsub yet. We hope to soon, but are also open to community contributions. :)

thanks for the answers, will try it!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ianrose14 picture ianrose14  路  3Comments

nfisher picture nfisher  路  3Comments

sharkyze picture sharkyze  路  4Comments

imkira picture imkira  路  4Comments

dragan-cikic-shortcut picture dragan-cikic-shortcut  路  3Comments