zyzyis
zyzyis

Reputation: 213

How to write an unit test for 'getCurrentTime()' function?

I am recently having one getter function which just returns the current Time using certain time format. Since it is returning the current time using some system API, I can't think of a way to write an unit test for this.

Can anyone give suggestion on that?

Upvotes: 0

Views: 376

Answers (3)

Rodney Gitzel
Rodney Gitzel

Reputation: 2710

The ideal solution is to not use the system time directly, and instead have all your code use a wrapper around System (assuming Java, say) which you can mock out. This may not be feasible, or easy.

A simpler approach would be to create a second method strictly to do the formatting, which takes the time as a parameter. You can then test formatting easily and thoroughly.

Then in your original method call the new method passing in the system time (e.g. System.currentTimeMillis()) and don't bother writing tests for it. There's nothing to go wrong that you can do anything about, at that point, so there's really nothing to test.

Upvotes: 1

Wouter de Kort
Wouter de Kort

Reputation: 39898

You need to separate the System API from your System under test.

A known way to do this is to use Dependency Injection. You inject a class into your time formatter that retrieves the current time.

In your unit tests you insert a Fake CurrentTime api that will return predefined values so you can check the result of your TimeFormatter. When you're running in production you use the System API.

Upvotes: 1

jglatre
jglatre

Reputation: 943

At least you can check if result is not null and if you call it twice, second result is greater than first.

Upvotes: 1

Related Questions