Unit Testing Dates and Times with Carbon

One area of my codebase at work that I had problems sufficiently testing were instances in my code base that had time based logic to them. Since I work in the manufacturing sector, lots of logic relies on knowing what the current, last, or next shift is. There are lots of edge cases that need tested around shift change, especially third shift, which starts before midnight, but for all the reporting and other facets of my software it is technically tomorrow.

So these time-dependant functions for the most part did not have useful, functional unit tests, until recently. In the past I would write my logic, cross my fingers and wait for the bug reports to come rolling in. I'm so thankful that I discovered this testing aid built in to the Carbon PHP library. (If you haven't used Carbon, stop reading and go check it out, I'll forgive you. It makes working with dates and times in PHP a walk in the park, it is one of the most useful libraries I use!)

So now you are wondering, "What is this wonderful function that will let me test my date/time based logic easier?" I'm glad you asked. It is the setTestNow() function built in to the Carbon api. Basically, this allows you to determine when now() is.