Deal with time dependencies in Tests

Las week we discovered that some of our test would “randomly” fail depending of the time of the day. After investigating the issue we found that the culprit was that the service being tested was taking decisions based on the current system time (DateTime.Now) leading to different outcomes through the day. So how do we deal with time dependencies in tests?

My first thought was creating an IClock interface and injecting an implementation to the service. It seemed like an overkill and then I googled enough to find a short and very simple solution in Ayende’s 2008 article: Dealing with time in tests

I’ll use .NET Core and xUnit to illustrate the problem and the proposed solution.

Now let’s start:

1. Create a test project
2. Create a SystemDateTime helper class
3. Create a Service with a dependency on time
4. Create the tests
5. Run the tests

You can get the code here: https://github.com/cmendible/dotnetcore.samples/tree/master/remove.datetime.dependency.test

Hope it helps!

5 thoughts on “Deal with time dependencies in Tests

  1. I don’t think an IClock interface would be overkill; mocking frameworks make it trivial to create and configure a fake IClock. Dependencies are typically abstracted with interfaces, and time is just another dependency. Having some dependencies modeled as interfaces and others as static members is inconsistent. Also, the approach you suggest here isn’t thread safe, and is likely to cause random test failures if the tests are executed in parallel.

    1. Hi Thomas,

      sometimes there is a need to find a balance between the simplicity, consistency and the trade offs of implementing a specific solution. In our specific case I had to choose a: 4 line solution, with no additional Mocking needed, for a widespread problem in a code base where we didn’t have the time to modify all the services constructors to inject an IClock, but where replacing all the calls with the static method was a matter of minutes.

      Thanks for pointing out that The solution isn’t thread safe. Although I didn’t have to face the multi-threading issue, I should have warned my readers about it.

Leave a Reply