Skip to content

Stravaig-Projects/Stravaig.Clock

Repository files navigation

Stravaig Clock

A set of packages to assist with automated tests when the current time is required in code.

For full documentation see: https://stravaig-projects.github.io/Stravaig.Clock/

Quick Start

  • In your application inject an IClock where needed.
  • Add the IClock to your service collection.
  • In your tests replace the clock with a FakeClock, and then assert that the date emitted by the FakeClock is the one used.
public class MyService
{
  private readonly IClock _clock;
  public MyService(IClock clock)
  {
    _clock = clock;
  }

  public Thing CreateTheThing()
  {
    return new Thing()
    {
      DateCreatedAt = _clock.UtcNow;
    }
  }
}

And in the test:

[TestFixture]
public class MyServiceTests
{
  [Test]
  public void ThingIsCreatedAtTheAppropriateTime()
  {
    var testTime = new DateTime(2023, 8, 12, 16, 16, 0, DateTimeKind.Utc);
    var fakeClock = FakeClock.SetTo(testTime);
    var service = new MyService(fakeClock);

    var thing = service.CreateTheThing();

    thing.DateCreatedAt.ShouldBe(testTime);
  }
}

Packages

About

An injectable clock to make it easier to unit test code that gets the current time

Resources

License

Stars

Watchers

Forks

Packages

No packages published