You Should Use Static Dates For Your Unit Tests

When writing unit tests for time-sensitive features, there are two ways you can define dates: dynamically or statically. When I say “dynamically defining dates,” I mean basing dates off of the current system time, as opposed to statically defined dates, which are hard-coded strings in the unit test.

Over the past few months, I’ve found that dates become much less of a pain to test when you use statically defined sample dates. They also lead to generally stronger test suites as a whole. Here are a few reasons why I think you should use static dates for your unit tests.

Catch Edge Cases Now, Not Later

When developing a feature, I want to make sure that it works with any given date. However, that doesn’t mean that each test I write for it has to handle any given date. By using the current system’s time for a test, I would only be able to test edge cases once that time came around. Sure, I might be able to cover more test cases by writing less code using the current system’s time, but I lose the ability to check edge cases each time I run the test suite.

By using static dates instead of the system time, I can have a test suite that consistently finds problems with my code around troublesome dates.

Don’t Disrupt Future Development

Whenever I use dynamic dates in unit tests, I find myself hitting edge cases a few weeks or even months later. By that time, I’ve moved on to other features.

Tests that fail after the initial development cycle of a feature can be problematic in a few different ways. First, the failing feature is not as fresh in my head as it was a few weeks ago. This causes me to waste more time debugging that section of the code than if I had tested for those edge cases during the initial development of that feature. Also, I might not even be on the project when the test fails, so someone else may have to deal with edge cases that were not properly tested before.

Be Confident That Your Feature Works

Unit tests are a great way to describe what a feature should do. By manually defining dates in unit tests, I show the behavior of a feature with the given date. If I were to use dynamic dates instead, these behaviors around edge cases would be much harder to see at first glance. I can be more confident that my feature will work with any given date if I manually define those dates.

Final Thoughts

These are some of the main reasons why I use static dates for my unit tests. By not depending on the current system time, my test suite is stronger and more helpful to my project. I hope some of these tips can help you properly test dates in your application.