Kent Rancourt
2 min readOct 1, 2020

--

Constructively... you made a lot of unnecessary work for yourself. Your end goal is to test the `UserDatabase` component. You've spoken quite a bit about dependency injection... `UserDatabase` only uses the `users` collection and nothing else. If you injected the collection instead of the whole DB client, you wouldn't have had to create the "DatabaseHelper" interface at all. You'd only need the `CollectionHelper` interface. And that's only the first bit of unnecessary work.

The second is that there should have been no need to create an implementation of the `CollectionHelper` interface (other than the mock). Since your implementation is just a proxy / pass-through, you could have skipped that. If the functions of the `CollectionHelper` interface had just -slightly- different signatures, the existing `*mongodb.Collection` type would already implement that new interface (sparing you a lot of work), even though it was defined after the fact.

To be fair, the approach above -might- have ended up giving mockery some grief, but with things so simplified, you probably don't need mockery at all and could have gotten by with a pretty simple hand-crafted mock implementation of `CollectionHelper` that allows you to inject behaviors for each of the functions at test-time. And that saves you the overhead of code generation as well-- because code generation IS overhead when you consider that if this were a real project with other contributors, you'd need to work out how to make the code generation seamless so that every time an interface is modified, the corresponding mock is re-generated as well.

Again, this is all intended in a constructive spirit. It seems this is a learning project. (We all have them.) So, humbly, here's an opportunity to learn new interfaces for existing implementations can save you a lot of work.

--

--

Kent Rancourt
Kent Rancourt

Written by Kent Rancourt

Kent is a founding engineer at Akuity, working primarily with Kubernetes, Argo CD, and other open source projects.

Responses (1)