Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to mock the DateTime.Now method?

Posted on 2014-09-11
6
Medium Priority
?
203 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
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.

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

704 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