An injectable and testable clock.
In the project where you set up your services, usually the entry project of your application, add the nuget package Stravaig.Clock.DependencyInjection
In your Startup
class, or where ever you build your IServiceCollection
, add the following:
1
services.AddClock();
In any project where you use the clock include the nuget package Stravaig.Clock.
Inject the IClock
in to your classes as you would any other dependency, e.g.
1
2
3
4
5
6
7
8
public class MyService
{
private readonly IClock _clock;
public MyService(IClock clock)
{
_clock = clock;
}
}
Then when you need to get the current time you can call the relevant method on IClock
. e.g.
1
2
3
4
5
6
7
public Thing CreateTheThing()
{
var thing = new Thing()
{
DateCreatedUtc = _clock.UtcNow,
};
}
In your test project you will need to add the Nuget package Stravaig.Clock.Testing.
In your test you will need to create a FakeClock
to inject into your class instead of using the regular Clock
the application will use when running.
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Test]
public void TestTheThing()
{
// Arrange
var createTime = new DateTime(2023, 8, 12, 14, 20, 0, DateTimeKind.Utc);
FakeClock fakeClock = FakeClock.SetTo(createTime);
var myService = new MyService(fakeClock);
// Act
var thing = myService.CreateTheThing();
// Assert
thing.DateCreatedUtc.ShouldBe(createTime);
}
Note: The above test uses Shouldly as the assertion framework.