Skip to content
Advertisement

PhpUnit: how to fake an outdated file?

I have a method in a class, which checks if a file is older than a day. It achieves this by getting the last change date of the file and comparing it with “now”:

JavaScript

I want to write a Unittest faking an outdated file. I tried to change the file date with touch:

JavaScript

The output gives me the information that in fact my file is from “Sep 23 11:58”, Yeay…..

But my test is failing and when I debug my file date is today and not September, the 23rd.

Using filemtime results in the same.

Is it possible to fake a file timestamp?

My system runs on an alpine linux.

Advertisement

Answer

Note you don’t have to create the file first, because touch does that for you. And there is a PHP built-in for touch(), you don’t have to shell exec:

JavaScript

This yields:

JavaScript

Applying your code but with filemtime:

JavaScript

Yields the desired truthy value:

JavaScript

However, this is a rather roundabout comparison. I’d just compare the timestamp values directly:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement