Skip to content
Maarten Mensink edited this page Dec 2, 2016 · 9 revisions

#Spring IT System.Clock

A few years ago we build this Clock to get rid of a frustration of testing code with DateTime in it. Clock was born. Today the 12th of july 2015 we wanted to share it with the community.

Basis usage

The basis usage of Clock

var container = new Container();
container.Register<IClock, ClockProvider>();

var clock = container.GetInstance<IClock>();
clock.Now.Should().BeCloseTo(DateTime.Now);

var currentDateTime = clock.Now; //with time component
var currentDate = clock.Today(); //with date component only time will be 00:00:00
var yesterday = clock.Yesterday(); //with date component only time will be 00:00:00
var tomorrow = clock.Tomorrow(); //with date component only time will be 00:00:00
var ticks = clock.Ticks(); //with date component only time will be 00:00:00

DateTime Extension

There are some basic extension methods for the DateTime

//Let's assume its 2015-1-15 17:00:00 
var startOfDay = clock.Now.StartOfDay(); //returns 2015-1-15 00:00:00
var endOfTheDay = clock.Now.EndOfDay(); //returns 2015-1-15 23:59:59

var startOfDay= clock.Now.StartOfMonth(); //returns 2015-1-1 00:00:00
var endOfMonth = clock.Now.EndOfMonth(); //returns 2015-1-31 23:59:59

Testing with IClock

With the IClock interface you can now easily Mock your dates. You can check out the unit test project for samples

[TestFixture]
public class ClockProviderTest
{
	private IClock _clockProvider;

	private class TestClock : IClock
	{
		internal static readonly DateTime TheClock = new DateTime(2014, 1, 1, 12, 0, 0);

		public DateTime Now => TheClock;
	}

	[SetUp]
	public void Setup()
	{


		_clockProvider = new TestClock();
	}

	[Test]
	public void Now()
	{
		var now = _clockProvider.Now;

		now.Should().Be(TestClock.TheClock);
	}
}
Clone this wiki locally