Solved

How to mock the DateTime.Now method?

Posted on 2014-09-11
6
149 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 74

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 74

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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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 74

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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now