Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing code that does date processing based on today's date

Tags:

When code processes dates based on the current date, testing should cover edge cases such as leap years as well as the more frequent month and year boundaries.

In our code we always get the current date deep down in our classes using DateTime.Now (.NET, in our case).

How can you unit test such code?

Is this where Dependency Injection becomes very useful?

Edit

This is a slight aside, but apparently the next version of Typemock will allow faking of DateTime.Now

https://blog.typemock.com/2009/05/mockingfaking-datetimenow-in-unit-tests.html

like image 381
Richard Ev Avatar asked Feb 19 '09 13:02

Richard Ev


People also ask

What does the timely rule of unit testing mean?

Timely: Unit tests should be written just before the production code that makes the test pass. This is something that you would follow if you were doing TDD (Test Driven Development), but otherwise it might not apply.

What is unit testing with real time example?

An example of a real-world scenario that could be covered by a unit test is a checking that your car door can be unlocked, where you test that the door is unlocked using your car key, but it is not unlocked using your house key, garage door remote, or your neighbour's (who happen to have the same car as you) key.

Can you unit test UI?

Unit Tests Don't Test The UI Most application users spend all of their time interacting with your program through it's UI, it's user interface. Unit tests are back-end tests, they can check that a calculation is correct, but they can't verify that the results display correctly to your user.


1 Answers

In our code we always pull out the current date using DateTime.Now (.NET, in our case). How can you unit test such code?

This is a dependency, and a non-deterministic dependency at that. You need to divide the responsibility of the code up a little more.

Before:

  • There is some code that uses the current datetime to do X.

After:

  • There should be some code that is responsible for getting the current datetime.
  • There should be some code that uses a datetime to do X.

These two sets of code should not be dependent on each other.

This pattern of seperating dependencies works for other cases as well (database, filesystem, etc).

like image 184
Amy B Avatar answered Oct 20 '22 10:10

Amy B