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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…