Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to mock the DateTime.Now method?

Posted on 2014-09-11
6
Medium Priority
?
215 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
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…

824 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