DateTimes

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 amount of days. How do we unit test the isNew() method? As we demonstrated in the implementation, it's difficult to reproduce specific flows in our test suites. What options do we have?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset