Image: https://www.theinformationlab.co.uk/2017/08/09/data-scaffolding-easy-steps-fill-missing-data/

Go: Mocking Google’s PubSub Message

Noam Tenne
2 min readJul 17, 2018

--

I wrote an application that used Google’s PubSub infrastructure as a messaging queue. Because Go is a Google language, the integration with PubSub was a breeze.

Testing was a whole different matter.

For integration testing, Google are nice enough to provide us with a PubSub emulator.

But I also wanted a deeper unit test to verify my interaction with the PubSub message itself. For example, a lightweight test that validates message acknowledgement or lack of.

The Message Struct

Is easy to mock. The ID , Data , Attributes and PublishTime fields are exported, so no problem there.

But I also want to mock the message’s ack state. We’ve got doneFunc and calledDone as an indication for this and they’re both unexported fields. As we all know, unexported fields cannot be set from outside so we need to

Mock your private parts.

That shouldn’t be too difficult, right? We can set them via reflection.

But then we’re hit with the following error
panic: reflect: reflect.Value.Set using value obtained using unexported field

OK, fine. We can’t willy nilly set an unexported field! We’ll create our own field with blackjack and hookers! And more important — a pointer to the original field.

Oh, snap! Another error!
panic: reflect.Value.UnsafeAddr of unaddressable value

We can’t get the address of the field because it’s unaddressable ¯\_(ツ)_/¯
Addressable value, it is!

Aaand victory is ours.

Happy hacking, everyone!

--

--