Code Smell 204 - Tests Depending on Dates
It is a good idea to assert something has happened in the future

TL;DR: Tests must be in full control and you can't manage time.
Problems
Fragile Tests
CI/CD Breaks
Solutions
Tests should be always in full environmental control.
Create a time source
Context
I read a Tweet about adding a fixed date to check for the removal of a feature flag (which is another code smell). The test will fail in an unpredictable way preventing releases and breaking CI/CD pipeline. There are also other bad examples we will never reach some date, tests running at midnight, different timezones, etc.
Sample Code
Wrong
class DateTest {
@Test
void testNoFeatureFlagsAfterFixedDate() {
LocalDate fixedDate = LocalDate.of(2023, 4, 4);
LocalDate currentDate = LocalDate.now();
Assertions.assertTrue(currentDate.isBefore(fixedDate) || !featureFlag.isOn());
}
}
Right
class DateTest {
@Test
void testNoFeatureFlags() {
Assertions.assertFalse(featureFlag.isOn());
}
}
Detection
[X] Semi-Automatic
We can check assertions based on time on our tests.
Tags
- Testing
Conclusion
Proceed with caution with tests and dates.
They are often a cause of mistakes.
Relations
More Info
Disclaimer
Code Smells are my opinion.
Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.
Christopher Alexander
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionGreat tip!
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





