Why is there no IDateTimeProvider in .NET, but does DateTime now have a getter?

I am currently writing unit test for a component that performs specific datetime authentication. I created an IDateTimeProvider interface that is used as a DateTime.UtcNow wraper, and business objects use the interface directly, not DateTime . It seems that the DateTime is a bit overloaded and should be split into a value and a thing that gets that value from the OS. I wonder if there is a specific reason not to have an IDateTimeProvider ( IClock ) interface in .NET?

+6
c # oop
source share
4 answers

Simply put: because large parts of BCL were not meant to be tested.

The same is true for generating random numbers in terms of "core" functionality - and many HTTP-related classes are much worse to fake :( At least in this case, it’s wise to just enter your own clock interface.

On the plus side, when Noda Time is ready to be used in production, it will not only provide a better API with date and time than BCL - it will be more convenient for testing :)

+7
source share

We consistently use the DateTimeProvider wrapper class, which, if necessary, can be overridden in a test context ...

+1
source share

http://learn.typemock.com/typemock-isolator/ can mock DateTime (and other mscorlib types), so DateTime.Now is not a problem again. But the disadvantage, of course, is that this can lead to the fact that developers will develop their material even worse, since this is not a problem for falsifying DateTime.Now!

Perhaps something like IDateTimeProvider is the best solution for such things.

But if you use a third-party library that is relayed, for example, DateTime TypeMock-Isolatior may be a solution / workaround.

Also Microsoft Research Moles / Stub is cool stuff: http://channel9.msdn.com/blogs/peli/moles-replace-any-net-method-with-a-delegate (shows how to replace any .NET method / property delegate - for example DateTime.Now; -))

0
source share

I posted this answer to another question, but it applies here if you are looking for an easy way to test DateTime.Now .

I like to create a public function that returns DateTime ( Func<DateTime> ) in a class that needs the current date / time, and set it to return DateTime.Now by default. Then, during testing, I overwrite it with a testing function that returns all the DateTimes that I want to test with.

 public class MyClass { public Func<DateTime> DateTimeNow = () => DateTime.Now; public void MyMethod() { var currentTime = DateTimeNow(); //... do work } } public class MyClassTest { public void TestMyMethod() { // Arrange var myClass = new MyClass(); myClass.DateTimeNow = () => new DateTime(1999, 12, 31, 23, 59, 59); // Act myClass.MyMethod(); // Assert // my asserts } } 
0
source share

All Articles