I have some unit tests that expects the ‘current time’ to be different than DateTime.Now and I don’t want to change the computer’s time, obviously.
What’s the best strategy to achieve this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The best strategy is to wrap the current time in an abstraction and inject that abstraction into the consumer.
Alternatively, you can also define a time abstraction as an Ambient Context:
This will enable you to consume it like this:
In a unit test, you can replace
TimeProvider.Currentwith a Test Double/Mock object. Example using Moq:However, when unit testing with static state, always remember to tear down your fixture by calling
TimeProvider.ResetToDefault().