DEV Community

Discussion on: Learn Go by writing tests: Dependency Injection

Collapse
 
biros profile image
Boris Jamot ✊ / • Edited

I see a lot of posts about hello world unit testing in Go but nothing really serious.
I've been learning Go for 2 months now, and I must admit that it's pretty straightforward, but I'm still struggling with "real" unit tests. To my opinion, a unit test MUST only test the output of a given function, and not its dependencies. That means you have to mock things. And that's here that it gets very complicated in Go. I'm a big fan of DI for the testability and the modularity of the code, but how to deal with a dependency that doesn't offer any interface ? Then you write your own interface to wrap your dependency. And then you realize that you need to create a second interface. And a third. And... You got me.
I'm using gin-gonic & uber-zap which are quite easy to mock. It's getting more complicated with jwt-go. And it's even worse with mgo.
Why no one talk about that ?
Does it mean that no one is writing unit tests for mgo ?

Collapse
 
quii profile image
Chris James

I see a lot of posts about hello world unit testing in Go but nothing really serious.

What's not serious about this? :)

And it's even worse with mgo.

I have used mgo. I would never write unit tests for mgo because it's someone else's code. Dont test other people's code. Test your interaction with it.

But how?

For those who dont know, mgo is a mongo driver for Go.

Forget about different classes of test or whatever. You want a bit of your code that can talk to the mongo db such as GetBankAccount(id string). Write a test for that. Inside it uses mgo, but that doesn't really matter, test the useful behaviour.

Mocking mgo gives you so little in terms of confidence your system works and if you decide you want to refactor to use a different library you suddenly have a bunch of useless tests.

Why no one talk about that ?

No one talks about it because it's too specific. You should be designing your software so that its as easy to test as the "not serious" examples you're reading.