Go For Punks!
Published in

Go For Punks!

How to test functions that use time.Now()

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.

Posts about Golang

Recommended from Medium

SQL Time-Savers: A Few Nifty Tips to Ease Your Querying

TryHackMe’s Overpass Level1

Separation of Concerns in Real Life Apps

asp net mvc 4 not permission use bulk load statement

How to create an image carousel slider in Flutter

The Tezos Post #2

Ping To google.com but not to facebook.com

Roman Numerals Converter Application (Python Flask) deployed on AWS EC2 with CloudFormation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Romenigue Thier

Romenigue Thier

Engenheiro da Computação aspirante a agilista.

More from Medium

Best OAuth Security Practices for Single Page Applications

GRPC vs Rest: Quick Comparison

How to Debug Efficiently for High-Level Languages

Introduction to gRPC