June 2017
Intermediate to advanced
394 pages
8h 52m
English
Because DateTimes are widely used in Entities, we think it's important to point out specific approaches on unit testing Entities that have fields with date types. Consider that a Post is new if it was created within the last 15 days:
class Post{ const NEW_TIME_INTERVAL_DAYS = 15; // ... private $createdAt; public function __construct($aContent, $title) { // ... $this->createdAt(new DateTimeImmutable()); } // ... public function isNew() { return (new DateTimeImmutable()) ->diff($this->createdAt) ->days <= self::NEW_TIME_INTERVAL_DAYS; }}
The isNew() method needs to compare two DateTimes; it's a comparison between the date when the Post was created and today's date. We compute the difference and check if it's less than the specified ...