Solved

How to mock the DateTime.Now method?

Posted on 2014-09-11
6
181 Views
Last Modified: 2014-09-12
I am using TDD and can't get my mocking of the DateTime.Now method working.  I found this post on the web and am trying to implement the solution: http://catchblock.com/blog/post/2012/03/05/How-to-mock-DateTimeNow-in-unit-tests.aspx

Here is my relevant code:
    public static class SystemTime
    {
        public static Func<DateTime> Now = () => DateTime.Now;
    }

    public partial class RequestProcessLogic
    {
        IReferralsModelContainerRepository _repository;
        EmployeeProfileRecord _emprec;

        public RequestProcessLogic() : this(new EF_ReferralsModelContainerRepository(), new EmployeeProfileRecord())
        { }
        public RequestProcessLogic(IReferralsModelContainerRepository repository, EmployeeProfileRecord emprec=null)
        {
            _repository = repository;
            _emprec = emprec;
        }
        public virtual NewReferralRequestModel PopulateNewRequestModel(Int32 referraltypeid, string uniquekeyvalues, Int32 employeeprofileid)
        {
            // Get ReferralType informataion for NewRequestMoel
            REF_ReferralType rt = _repository.GetReferralType(referraltypeid);

            // Return null if no data found
            if (rt == null)
                return null;

            // Parse uniquekeyvalues
            string[] keyvalues = uniquekeyvalues.Split(',');

            // Populate the NewRequestModel
            NewReferralRequestModel model = new NewReferralRequestModel();
            model.ReferralTypeID = rt.ReferralTypeID;
            model.ReferralTypeName = rt.ReferralTypeName;
            model.ReferralGroupName = rt.REF_ReferralGroup.ReferralGroupName;
            model.ReferralTypeMoreInfoLink = rt.ReferralTypeMoreInfoLink;
            model.ReferralTypeGeneralGuidelines = rt.ReferralTypeGeneralGuidelines;
            model.ReferralSynopsis = null;
            model.ReferralComments = null;
            model.ReferralPriority = PriorityType.Normal;
            model.ReferralRequesterProfileID = employeeprofileid;
            model.ReferralEstimatedCompletionDate = CalculateSLACompletionDate(DateTime.Now, rt.ReferralTypeSLA);
            model.ReferralTypeSLA = rt.ReferralTypeSLA;
            model.ReferralTypeRoute = rt.ReferralTypeRoute;
            model.ReferralTypeRequiresApproval = rt.ReferralTypeRequiresApproval;

            return model;
        }

        public virtual DateTime CalculateSLACompletionDate(DateTime datetocalculatefrom, int sla)
        { 
            // Add SLA calculation code
            return datetocalculatefrom;
        }
    }

Open in new window


Unit Testing Code
        [TestMethod]
        public void PopulateNewRequestModel_Returns_Model_If_ReferralTypeID_Is_Found_In_ReferralType_Table()
        {
            // Arrange
            InMemoryReferralsModelContainterRepository repository = imr.PopulateInMemoryRepository();
            // Mock the EmployeeProfileRecordClass
            var mockEmployeeProfileRecord = new Mock<EmployeeProfileRecord>(epimr);
            mockEmployeeProfileRecord
                .Setup(epr => epr.GetEmployeeFirstNameLastName(5810))
                .Returns("");
            SystemTime.Now = () => Convert.ToDateTime("8/18/2014 12:00 PM"); 
            RequestProcessLogic sut = new RequestProcessLogic(repository, mockEmployeeProfileRecord.Object);

            // Act
            NewReferralRequestModel result = sut.PopulateNewRequestModel(10, "DRC Policy, 12345678, 2/14/14", 5810);

            // Assert
            Assert.AreEqual(10, result.ReferralTypeID);
            Assert.AreEqual("URS Test Referral", result.ReferralTypeName);
            Assert.AreEqual("Testing", result.ReferralGroupName);
            Assert.AreEqual(null, result.ReferralTypeMoreInfoLink);
            Assert.AreEqual("Referral Guidelines", result.ReferralTypeGeneralGuidelines);
            Assert.IsNull(result.ReferralSynopsis);
            Assert.IsNull(result.ReferralComments);
            Assert.AreEqual(PriorityType.Normal, result.ReferralPriority);
            Assert.AreEqual(5810, result.ReferralRequesterProfileID);
            Assert.AreEqual(Convert.ToDateTime("8/18/2014 12:00 PM"), result.ReferralEstimatedCompletionDate);
            Assert.AreEqual(2880, result.ReferralTypeSLA);
            Assert.AreEqual("RequestProcess", result.ReferralTypeRoute);
            Assert.AreEqual(true, result.ReferralTypeRequiresApproval);
}

Open in new window


The call to DateTIme.Now returns the current date/time.  How do I set this up so when testing I can set the datetime to be returned?  Any help is greatly appreciated!
0
Comment
Question by:dyarosh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40318089
How do I set this up so when testing I can set the datetime to be returned?
I'm confused:  Isn't that exactly what you are doing in line 11 of the 2nd snippet?
0
 

Author Comment

by:dyarosh
ID: 40319103
That is what I am trying to do but when I make the call to DateTime.Now it returns the real time not the time I set.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40319184
Where are you actually using this SystemTime class? I see where you assign to it, but I don't see anywhere else that you refer to it.
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:dyarosh
ID: 40319269
I make a call to DateTime.Now in the PopulateNewRequestModel method:

model.ReferralEstimatedCompletionDate = CalculateSLACompletionDate(DateTime.Now, rt.ReferralTypeSLA);

I tried replacing DateTime.Now with SystemTime.Now but then I get the following Compiler error and I can't figure out how to get rid of it.

Error      2      The best overloaded method match for 'UniversalReferrals.BusinessLogic.RequestProcessLogic.CalculateSLACompletionDate(System.DateTime, int)' has some invalid arguments      
Error      3      Argument 1: cannot convert from 'System.Func<System.DateTime>' to 'System.DateTime'
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40319355
Invoke it:

CalculateSLACompletionDate(SystemTime.Now()...

Open in new window

0
 

Author Closing Comment

by:dyarosh
ID: 40319491
Figures it would be something stupid that I wasn't doing.  Thank you so much.  That solved my problem!
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question