Your class depends on external resource, which is current system time. Thus you are not testing class in isolation, which gives you problem you faced. You should mock DateTime.Now
(some unit-testing frameworks allow mocking static members - e.g. JustMock), or create abstract dependency, which will provide time to your class:
public interface ITimeProvider
{
DateTime CurrentTime { get; }
}
As Mark Seemann suggests here, you can use static instance of this abstraction to avoid passing this dependency to each class which needs to get current time, but that will make dependency implicit (so its up to you to decide which way to go):
public class TimeProvider : ITimeProvider
{
private static ITimeProvider _instance = new TimeProvider();
private TimeProvider() { }
public static ITimeProvider Instance
{
get { return _instance; }
set { _instance = value; } // allows you to set mock
}
public DateTime CurrentTime
{
get { return DateTime.Now; }
}
}
Usage will be easy
var date = TimeProvider.Instance.CurrentTime;