Solved

How to mock the DateTime.Now method?

Posted on 2014-09-11
6
154 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
index Out OF Range Exception error 4 53
IO.FileSystemWatcher dies when used in Powershell 1 44
Problem to error 4 43
Eagerly loading related objects in entity framework 5 24
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…
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

932 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

9 Experts available now in Live!

Get 1:1 Help Now