ghost_king
ghost_king

Reputation: 930

Unit Testing with a DateTime

I am unit testing with a date but the build fails because the date has a timestamp in it. How would I remove it to enable the testing works?

 DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Now).Returns(mockDateTime)

The mockDateTime returns 4/18/2025 12:00:00 AM but I only want 4/18/2025

Upvotes: 0

Views: 121

Answers (1)

Nathan Tregillus
Nathan Tregillus

Reputation: 6334

instead of (m => m.Now), have you tried (m=> m.Today) instead?

DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Today).Returns(mockDateTime)

also, DateTimes always have a time component. Are you doing any toString actions in your code? you should probably just check ToShortDateString(), which is what will give you just the date part of the datetime: https://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring(v=vs.110).aspx

Upvotes: 3

Related Questions