Today's Recommended articles compare technical details and talk about how to simulate the business process logic caused by changes in date or time during unit testing. The problem, at first, seems relatively simple, but the solution is relatively complex.
The author of this article, Jerrie Pelser, has recently encountered a problem that requires periodic checks on the expiration of a user's subscription and sending reminders to users within one week, 3 days, and 1 days prior to expiration. Of course the data access component and the mail sending component can mock, so what is the date and time to handle?
The author briefly describes several alternative ways:
- Change the system clock. It's straightforward, but it's not a good idea. The author explains the disadvantages of this approach in detail.
- The current time is passed. That is, modify the method signature to accept the time parameter so that the expected time is passed in when the unit is tested. Although effective, but not flexible enough.
- Create a clock service. Based on the above method, a clock service interface is defined, and the normal operation is injected into a system clock, and the unit test mocks one (using Nsubstitute as a mock frame) for the desired time.
- The final way is to actually use a library of Noda time. This library is actually implemented in the way mentioned above, but you can use it directly.
The original address is: Http://www.jerriepelser.com/blog/unit-testing-with-dates
How to simulate dates and times during unit testing