Async-capable Ambient Context Pattern for unit/integration testable DateTimes in C# .NET
For any and all future updates, the code releases will utilizing SemVer semantic versioning style.
Conveniently, eladaus.TestableTime is available on NuGet as eladaus.TestableTime
. Install it from NuGet Package Manager Console with:
Install-Package eladaus.TestableTime
- None currently
The TestableTime library is a modernized, async-capable implementation of a DateTime provider context. It allows developers to retrieve DateTime.UtcNow values in code under normal execution operations but also to mock / programmatically assign the point-in-time for unit testing operations.
It is modelled on the Ambient Context Model (see dvoituron.com in links below) however that code fails under modern asynchronous scenarios due to thread changes during execution.
Using the new AsyncLocal concept, we can now pass a predefined DateTime instance through chained/nested async logic during unit and integration testing.
var fakeDate = new DateTime(1981, 08, 20, 0, 0, 0, DateTimeKind.Utc);
using var innerClock = new DateTimeUtcProviderContext(
fakeDate
);
var resultFromLocalContext = DateTimeUtcProvider.UtcNow;
var resultFromNestedCalls = await new MyAsyncClass().DoSomeAsyncThingReturnTheDate();
Assert.Equal(resultFromLocalContext, resultFromNestedCalls);
Assert.Equal(resultFromLocalContext, fakeDate);