How to simulate dates and times during unit testing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.