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?
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?
To test a code that depends on the
System.DateTime
, thesystem.dll
must be mocked.There are two framework that I know of that does this. Microsoft fakes and Smocks.
Microsoft fakes require visual studio 2012 ultimatum and works straight out of the compton.
Smocks is an open source and very easy to use. It can be downloaded using NuGet.
The following shows a mock of
System.DateTime
:I got same problem, but i was thinking we should not use the set datetime things on the same class. because it could lead to misuse one day. so i have used the provider like
For tests, at test project made a helper which will deal with set things,
on code
and on tests
But need to remember one thing, sometime the real DateTime and provider's DateTime doesn't act same
I assumed the deference would be maximum TimeSpan.FromMilliseconds(0.00002). But most of the time it's even less
Find the sample at MockSamples
Moles:
Disclaimer - I work on Moles
Using
ITimeProvider
we were forced to take it into special shared common project that must be referenced from the rest of other projects. But this complicated the control of dependencies.We searched for the
ITimeProvider
in the .NET framework. We searched for the NuGet package, and found one that can't work withDateTimeOffset
.So we came up with our own solution, which depends only on the types of the standard library. We're using an instance of
Func<DateTimeOffset>
.How to use
How to register
Autofac
(For future editors: append your cases here).
How to unit test
Maybe less Professional but simpler solution could be make a DateTime parameter at consumer method.For example instead of make method like SampleMethod , make SampleMethod1 with parameter.Testing of SampleMethod1 is easier
Mock Objects.
A mock DateTime that returns a Now that's appropriate for your test.