Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...