Example: https://play.golang.org/p/DmAN1Kxi7VD

So I started growing fond of a new pattern in my Go code. Not sure if it is 
an antipattern for go or not but here is a quick description to see what 
everyone thinks:

In order to properly unit test a lot of code, sometimes you have to 
decouple some of the dependencies. The most common (only?) way I’ve seen 
this done in other code bases is by passing some sort of interface and it 
is often called XManager. And you have to pass this manager every time you 
want to use the function. This makes it easy to pass a MockXManager in a 
unit test. However, it is very annoying to have to go through all of those 
steps sometimes. More recently I wanted to mock time.Sleep so that my unit 
tests don’t take several minutes to complete. At first I went for the tried 
and true YManager approach but it just felt so overengineered. At the same 
time I needed to mock out time.Sleep.

So a couple weeks ago I started using variadic functions to pass optional 
arguments. I decided last night to use this to pass an optional mock sleep 
method. So when you are not in unit tests you don’t have to think about it. 
You only have to add like 4 or 5 lines of code to set up the default 
argument if not supplied. In the tests I was able to pass my own sleep 
method that did what I needed instantly.

This works really good when you have a single thing you need to customize 
but it can also work well if you have multiple dependencies. In the case of 
multiple dependencies you can use the same approach but with a struct 
instead of a single mocked function. This way you can set up the default 
behavior without app code having to pass any manager. In unit tests you 
simply supply the last optional parameter.

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 

Reply via email to