# Code Smell 204 - Tests Depending on Dates

> TL;DR: Tests must be in full control and you can't manage time.

# Problems

- Fragile Tests

- CI/CD Breaks

# Solutions

1. Tests should be always in full environmental control.

2. Create a time source

# Context

I read a [Tweet](https://twitter.com/housecor/status/1639975667713409030) about adding a fixed date to check for the removal of a feature flag (which is another [code smell](https://maximilianocontieri.com/code-smell-29-settingsconfigs)).
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

[Gist Url]: # (https://gist.github.com/mcsee/7e96669a0239ea203c90423e2e08b22d)
```java
class DateTest {
    @Test
    void testNoFeatureFlagsAfterFixedDate() {
        LocalDate fixedDate = LocalDate.of(2023, 4, 4);
        LocalDate currentDate = LocalDate.now();        
        Assertions.assertTrue(currentDate.isBefore(fixedDate) || !featureFlag.isOn());
    }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/3ccfe6623e9eea63c135afa59c4dbf4f)
```java
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

%[https://maximilianocontieri.com/code-smell-52-fragile-tests]

# More Info

%[https://twitter.com/housecor/status/1639975667713409030]

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).
  
* * *

> 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_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
