• Code
  • Tags
  • Users
  • Titles
  • Log in
  • Feedback
  • FAQ
Share Code
Welcome to ForkCan.com

ForkCan is all about sharing code in a social way.

Discuss, debate or argue with other devs about their or your own code.

Give other devs feedback or make a Fork (Make a better version of a shared code).

Rate the code, if you use the code mark it as used so others can see if the shared code is used by someone.

Help each other to be better devs and to be more productive.


Features not working yet:

Flag a post


QR Code

Tiny Url

http://4kcan.com/s/NTg1

Testable DateTime.Now

A DateTime.Now representation that can be alterd during testing.

1
1.04k 0 0 0 0 0

If you have a pice of code that is dependant of the current time you usually use the DateTime.Now property. But when writing tests to that piece of code you are unable to stub or mock DateTime.Now, since it's a static call.

Therefore I created this:

public static class SystemTime
{
    private static Func<DateTime> Time = () => DateTime.Now;

    public static DateTime Now
    {
        get { return Time(); }
    }

    /// <summary>
    /// Resets SystemTime.Now to return DateTime.Now
    /// </summary>
    public static void Reset()
    {
        Time = () => DateTime.Now;
    }
    /// <summary>
    /// Fix the time to fixedTime. All calls to SystemTime.Now will return fixedTime
    /// </summary>
    /// <param name="value"></param>
    public static void FixTo(DateTime fixedTime)
    {
        Time = () => fixedTime;
    }
    /// <summary>
    /// Fix the time to time. All calls to SystemTime.Now will return time offsetted with the time since this method was last called
    /// </summary>
    /// <param name="value"></param>
    public static void SetTo(DateTime time)
    {
        var offset = time - DateTime.Now;
        Time = () => DateTime.Now + offset; 
    }   
 }

This makes it possible to write tests that look like this:

public void MyUnitTest()
{
    SystemTime.FixTo(new DateTime(2011, 2, 15, 18, 0, 0));

    var anObject = CallToTimeDependantMethod1();   

    SystemTime.FixTo(new DateTime(2011, 2, 16, 20, 0, 0));

    var result = CallToTimeDependantMethod2(anObject);  

    Assert.Equal(new Timespan(1, 2, 0, 0), result.Duration);
}

Share: twitter | facebook   Action: used | fork | flag

c#

Mark 'c#' tag as 'like'

Mark 'c#' tag as 'ignore'

datetime

Mark 'datetime' tag as 'like'

Mark 'datetime' tag as 'ignore'

testing

Mark 'testing' tag as 'like'

Mark 'testing' tag as 'ignore'

unittesting

Mark 'unittesting' tag as 'like'

Mark 'unittesting' tag as 'ignore'


 @adam.lith "I'm a Forker"
400
February 11, 2011 4:45 PM
edited February 22, 2011 8:27 AM

Fork

 Testable DateTime.Now -  @adam.lith Friday 11, 2011 4:45 PM


0 Feedback


You must log in before you can give any feedback


0 Discussion(s)

Newest Oldest

You must log in before you can post a comment

Squeed
Made by: Fredrik Normén 2010