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?
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
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.
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.
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.
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:
After:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With