How to test functions that use time.Now()

Romenigue Thier
Go For Punks!

--

A lot of times we write functions and methods that use standard packages. But, when we goes to write the unit test for this functions the difficult appears. The best example about this is the time.Now()

In the beginning is necessary understand what the function written does and why the function time.Now() is needed inside it. Is really need a function to read the “now time”?
This article doesn’t have the answer about it, is your job understand “the why”, but here you can understand how to test the function that use it.

Let’s go!

A simple example

How can I test the function whatTimeIsItNow ?

In this example we just print the string returned for function whatTimeIsItNow, but how can I test this function?

Applying functional paradigm concept

Some sources says that Golang is a multi-paradigm language. I don’t know if this is really true, but we can use functions as arguments in the functions/methods.

Using the example above we can modify it and pass the time.Now as argument for the function. This will enable the function to execute a lot of variants of time functions and turn the unit test very simple to create.

Pass time.Now as argument to function

Now, is very simple to create a unit test for the function whatTimeIsIt (the name of function is changed because the time.Now is an argument and not more the main behavior of function).

TIP: Beautify the function using a custom type

Is strongly recommended use a custom type as argument because is very ugly use funcTime func() time.Time, this is not exactly readable and a custom type can be used in a lot of functions in your code. Follow the example:

Conclusion…

When you need to test functions that use builtin functions, like time.Now(), try to see the builtin function as an argument, apply the functional paradigm, probably this will make your code more reusable, dynamic and testable.

--

--

Romenigue Thier
Go For Punks!

Computer Enginner, Golang Enthusiast and Development Manager