DEV Community

Cover image for Tests with time
Kiolk
Kiolk

Posted on

Tests with time

I encountered the issue when my tests passed locally, but some of them failed on CI. Initially, I thought it was a problem with incorrect configuration of the running task or pipeline environment. I tried several solutions, but none worked. Surprisingly, it was only after that I decided to check which tests had failed. The issue was clear: it was related to time.
Failed tests
These tests cover the logic of parsing a string into LocalDateTime.  Parsing involves local time, which requires information about the time zone. I get this information from a static method that returns the time zone of the running environment: TimeZone.currentSystemDefault(). In tests, I use a string with a specific time and assert against a time related to my time zone. As a result, the tests passed on my local machine but failed on the CI machine, which operates in a different time zone. 

The solution was obvious: I need to provide a specific time zone for the tests to make them independent of the environment. To achieve this, I needed to extract the logic of obtaining time zone information as a dependency, allowing it to be configured for tests.

fun Any.parsToLocalDateTime(timeZone: TimeZone = TimeZone.currentSystemDefault()): LocalDateTime? {
Enter fullscreen mode Exit fullscreen mode

You can find more useful content on my LinkedIn page, on X, in Medium or Mastodon.

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay