The code below I threw together to mock a time interface that you can use for your unit tests. using this you can set your time to either the real time or a fake time that you specify. I often use this method when unit testing. It's called Dependency injection or constructor injection which is very useful for unit testing.
class Hotel
{
public DateTime ClosingTime = DateTime.ParseExact("17:00:00", "HH:ii:ss", CultureInfo.InvariantCulture);
public IStubClock Clock;
public bool IsOpen
{
get
{
return Clock.Now.TimeOfDay <= ClosingTime.TimeOfDay;
}
}
public Hotel(IStubClock clock)
{
Clock = clock;
}
}
Using this interface you can mock any DateTime.Now structure
public interface IStubClock
{
DateTime Now { get; }
}
A fake variant
public class FakeClock : IStubClock
{
private DateTime _now;
public DateTime Now
{
get
{
return _now;
}
}
public FakeClock(DateTime now)
{
_now = now;
}
}
And a real variant
public class RealClock : IStubClock
{
public DateTime Now
{
get
{
return DateTime.Now;
}
}
}
and then you can use them in your tests doing something like this
class Program
{
static void Main(string[] args)
{
IStubClock fakeClock = new FakeClock(new DateTime(1, 1, 1, 10, 0, 0)); //time is set to 10am
IStubClock realClock = new RealClock(); //time is set to whatever the time now is.
Hotel hotel1 = new Hotel(fakeClock); //using fake time
Hotel hotel2 = new Hotel(realClock); //using the real time
}
}