I've tests where I've to check whether current time and current date/time is correctly returned by my APIs through automation.

Suppose, getCurrentTime() returns current time in format HH:MM:SS (A/P)M and getCurrentDateTime() returns current date/time in format DD/MM?YYYY HH:MM:SS (A/P)M

In automation, I'm storing current time like -

actualCurrentTime=getCurrentTime() suppose this returns 03:25:35 AM

and after above call, I make java API call to get expectedCurrentTime and it'll return with differences of one or two seconds like 03:25:37 AM

Now, if I add assertion

Assert.assertEquals(actualCurrentTime, expectedCurrentTime);

This will fail because time is differing with few seconds. This is also true for current date/time because it contains time part.

I'm confused how to automate this or what approach should be used to automate this.

2 Answers 2


I guess what your API-under-test does under the hood is basically use the standard date and clock methods of whatever language the API is written in to read the system clock and pass on whatever it gets from there to the API caller. So essentially the approach you described is testing the system clock, which is probably not what you want to do.

If I were testing your getCurrentTime(), I would probably just make sure that if the API is called twice, the second call returns a greater value than the previous one (which would show that the time is actually being measured and that it's not going backwards).

  • 1
    I like this better than a range of a couple of seconds, because the range now is 2 seconds, but could be 30 seconds in the future leading to a flaky test. Commented Jan 5, 2017 at 11:22

Your problem statement is:

  • You want to compare actual time against expected time, but there is a time difference between getCurrentTime() and getExpectedCurrentTime(), therefore, your results never match.

Without looking at your source code, I think there is something else going on, as for Java, 2 seconds is a long time. Can you measure how much time does it take for your API call, e.g. getExpectedCurrentTime() to be executed?

My personal recommendation is, based on how critical your application is, and if you are confident that this time delay is almost a constant, you can add a two-second tolerance to your code, e.g. Assert.assertEquals(actualCurrentTime + 2 seconds, expectedCurrentTime); Of course, this line of code is pseudo, please do not copy and paste.

  • 1
    Instead of assuming fixed delay (2 seconds) I would rather check: assertThat(Math.abs(actualCurrentTime - expectedCurrentTime), lessThan(2)));
    – dzieciou
    Commented Jan 5, 2017 at 11:55
  • @dzieciou, yeah, your approach is better.
    – Yu Zhang
    Commented Jan 5, 2017 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.