Mocking objects using testify mock objects

Go already has a built-in system for building mock objects: interfaces. Most testing libraries that implement mocking work by temporarily “monkey patching” functions and passing in dynamic objects which do nothing.

In go, you would typically define an interface that describes the object that your library deals with. Your test script would deliver a simple version that doesn’t do anything except perhaps collect information on its interaction with the code being tested.

This is already sufficient for most traditional uses of mocking. It’s also usually possible to convert your functions from ones that take concrete objects to ones that take interfaces. As a bonus, you’ll probably be making the boundary between your code and the other module more explicit and interchangable with alternate implementations.

You may be able to simplify the building of your test classes with the testify/mock library. It allows you to very quickly build out test objects which collect which of these stubbed function calls are used, as well as provide dynamic, per-test stuffing of results.

It works reasonably for this purpose.

Share Comments
comments powered by Disqus