<p>I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?</p>

[{'answer_id': 43716, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 4, 'selected': False, 'text': "<p>I think creating a separate clock class for something simple like getting the current date is a bit overkill. </p>\n\n<p>You can pass today's date as a parameter so you can input a different date in the test. This has the added benefit of making your code more flexible.</p>\n"}, {'answer_id': 43718, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': -1, 'selected': False, 'text': '<p>Have you considered using conditional compilation to control what happens during debug/deployment?</p>\n<p>e.g.</p>\n<pre><code>DateTime date;\n#if DEBUG\n  date = new DateTime(2008, 09, 04);\n#else\n  date = DateTime.Now;\n#endif\n</code></pre>\n<p>Failing that, you want to expose the property so you can manipulate it, this is all part of the challenge of writing <em>testable</em> code, which is something I am currently wrestling myself :D</p>\n<h3>Edit</h3>\n<p>A big part of me would preference <a href="https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43720">Blair\'s approach</a>. This allows you to &quot;hot plug&quot; parts of the code to aid in testing. It all follows the design principle <em>encapsulate what varies</em> test code is no different to production code, its just no one ever sees it externally.</p>\n<p>Creating and interface may seem like a lot of work for this example though (which is why I opted for conditional compilation).</p>\n'}, {'answer_id': 43720, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 8, 'selected': True, 'text': '<p>My preference is to have classes that use time actually rely on an interface, such as</p>\n\n<pre><code>interface IClock\n{\n    DateTime Now { get; } \n}\n</code></pre>\n\n<p>With a concrete implementation</p>\n\n<pre><code>class SystemClock: IClock\n{\n     DateTime Now { get { return DateTime.Now; } }\n}\n</code></pre>\n\n<p>Then if you want, you can provide any other kind of clock you want for testing, such as</p>\n\n<pre><code>class StaticClock: IClock\n{\n     DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }\n}\n</code></pre>\n\n<p>There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a <a href="http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx" rel="noreferrer">Static Gateway Pattern</a>).</p>\n\n<p>Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that\'s just going to introduce pain on other levels.</p>\n\n<p>Also, using <code>DateTime.Now</code> and including it in your calculations doesn\'t just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won\'t allow you to test those scenarios. Or at least not whenever you want.</p>\n'}, {'answer_id': 43721, 'author': 'Daren Thomas', 'author_id': 2260, 'author_profile': 'https://Stackoverflow.com/users/2260', 'pm_score': 2, 'selected': False, 'text': "<p>You could inject the class (better: method/<strong>delegate</strong>) you use for <code>DateTime.Now</code> in the class being tested. Have <code>DateTime.Now</code> be a default value and only set it in testing to a dummy method that returns a constant value.</p>\n\n<p><strong>EDIT:</strong> What Blair Conrad said (he has some code to look at). Except, I tend to prefer delegates for this, as they don't clutter up your class hierarchy with stuff like <code>IClock</code>...</p>\n"}, {'answer_id': 43731, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 6, 'selected': False, 'text': '<p>Ayende Rahien <a href="http://www.ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" rel="noreferrer">uses</a> a static method that is rather simple...</p>\n\n<pre><code>public static class SystemTime\n{\n    public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;\n}\n</code></pre>\n'}, {'answer_id': 52077, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 4, 'selected': False, 'text': '<p>The key to successful unit testing is <strong>decoupling</strong>. You have to separate your interesting code from its external dependencies, so it can be tested in isolation.  (Luckily, Test-Driven Development produces decoupled code.)</p>\n\n<p>In this case, your external is the current DateTime.  </p>\n\n<p>My advice here is to extract the logic that deals with the DateTime to a new method or class or whatever makes sense in your case, and pass the DateTime in.  Now, your unit test can pass an arbitrary DateTime in, to produce predictable results.</p>\n'}, {'answer_id': 2183744, 'author': 'Pawel Lesnikowski', 'author_id': 80894, 'author_profile': 'https://Stackoverflow.com/users/80894', 'pm_score': 3, 'selected': False, 'text': '<p>I\'d suggest using IDisposable pattern:</p>\n\n<pre><code>[Test] \npublic void CreateName_AddsCurrentTimeAtEnd() \n{\n    using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))\n    {\n        string name = new ReportNameService().CreateName(...);\n        Assert.AreEqual("name 2010-12-31 23:59:00", name);\n    } \n}\n</code></pre>\n\n<p>In detail described here:\n<a href="http://www.lesnikowski.com/blog/index.php/testing-datetime-now/" rel="noreferrer">http://www.lesnikowski.com/blog/index.php/testing-datetime-now/</a></p>\n'}, {'answer_id': 2183833, 'author': 'João Angelo', 'author_id': 204699, 'author_profile': 'https://Stackoverflow.com/users/204699', 'pm_score': 4, 'selected': False, 'text': '<p>Another one using Microsoft Moles (<a href="http://research.microsoft.com/en-us/projects/moles/" rel="noreferrer">Isolation framework for .NET</a>).</p>\n\n<pre><code>MDateTime.NowGet = () =&gt; new DateTime(2000, 1, 1);\n</code></pre>\n\n<blockquote>\n  <p>Moles allows to replace any .NET\n  method with a delegate. Moles supports\n  static or non-virtual methods. Moles\n  relies on the profiler from Pex.</p>\n</blockquote>\n'}, {'answer_id': 20906399, 'author': 'mmilleruva', 'author_id': 1301147, 'author_profile': 'https://Stackoverflow.com/users/1301147', 'pm_score': 5, 'selected': False, 'text': '<p>Using Microsoft Fakes to create a shim is a really easy way to do this. Suppose I had the following class:</p>\n\n<pre><code>public class MyClass\n{\n    public string WhatsTheTime()\n    {\n        return DateTime.Now.ToString();\n    }\n\n}\n</code></pre>\n\n<p>In Visual Studio 2012 you can add a Fakes assembly to your test project by right clicking on the assembly you want to create Fakes/Shims for and selecting "Add Fakes Assembly"</p>\n\n<p><img src="https://i.stack.imgur.com/i7wVa.jpg" alt="Adding Fakes Assembly"></p>\n\n<p>Finally, Here is what the test class would look like: </p>\n\n<pre><code>using System;\nusing ConsoleApplication11;\nusing Microsoft.QualityTools.Testing.Fakes;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace DateTimeTest\n{\n[TestClass]\npublic class UnitTest1\n{\n    [TestMethod]\n    public void TestWhatsTheTime()\n    {\n\n        using(ShimsContext.Create()){\n\n            //Arrange\n            System.Fakes.ShimDateTime.NowGet =\n            () =&gt;\n            { return new DateTime(2010, 1, 1); };\n\n            var myClass = new MyClass();\n\n            //Act\n            var timeString = myClass.WhatsTheTime();\n\n            //Assert\n            Assert.AreEqual("1/1/2010 12:00:00 AM",timeString);\n\n        }\n    }\n}\n}\n</code></pre>\n'}, {'answer_id': 26994291, 'author': 'tugberk', 'author_id': 463785, 'author_profile': 'https://Stackoverflow.com/users/463785', 'pm_score': 2, 'selected': False, 'text': '<p>Simple answer: ditch System.DateTime :) Instead, use <a href="https://www.nuget.org/packages/NodaTime" rel="nofollow">NodaTime</a> and it\'s testing library: <a href="https://www.nuget.org/packages/NodaTime.Testing" rel="nofollow">NodaTime.Testing</a>.</p>\n\n<p>Further reading: </p>\n\n<ul>\n<li><a href="http://nodatime.org/unstable/userguide/testing.html" rel="nofollow">Unit testing with Noda Time</a></li>\n<li><a href="http://www.tugberkugurlu.com/archive/dependency-injection-inject-your-dependencies-period" rel="nofollow">Dependency Injection: Inject Your Dependencies, Period!</a></li>\n</ul>\n'}, {'answer_id': 51064402, 'author': 'Pawel Wujczyk', 'author_id': 9107834, 'author_profile': 'https://Stackoverflow.com/users/9107834', 'pm_score': 1, 'selected': False, 'text': '<p>I faced this situation so often, that I created simple nuget which exposes <strong>Now</strong> property through interface.</p>\n\n<pre><code>public interface IDateTimeTools\n{\n    DateTime Now { get; }\n}\n</code></pre>\n\n<p>Implementation is of course very straightforward </p>\n\n<pre><code>public class DateTimeTools : IDateTimeTools\n{\n    public DateTime Now =&gt; DateTime.Now;\n}\n</code></pre>\n\n<p>So after adding nuget to my project I can use it in the unit tests</p>\n\n<p><a href="https://i.stack.imgur.com/g8GrG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g8GrG.png" alt="enter image description here"></a></p>\n\n<p>You can install module right from the GUI Nuget Package Manager or by using the command:</p>\n\n<pre><code>Install-Package -Id DateTimePT -ProjectName Project\n</code></pre>\n\n<p>And the code for the Nuget is <a href="https://github.com/pwujczyk/DateTimePT" rel="nofollow noreferrer">here</a>.</p>\n\n<p>The example of usage with the Autofac can be found <a href="https://github.com/pwujczyk/CalculateEmailsPT" rel="nofollow noreferrer">here</a>.</p>\n'}]
['https://Stackoverflow.com/questions/43711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1404/']