Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

darkninja462's avatar

Unit testing Task Scheduling?

Hi All, I'm currently writing a Task Schedule, which is defined by calling a closure within the Kernel schedule function as described by the docs.

The basic flow is

$schedule->call(
    function () { 
        // delete some users where they match the criteria
        // email the results
    }
)
    ->timing()
    ->name("")
    ->withoutOverlapping();

I have simplified the code so easier to post but the basic flow is that.

I was wondering what is the best way to unit test this? or is there a better way to do this so it is easier to be unit tested?

Regards -Darkninja462

0 likes
5 replies
ifpingram's avatar

@darkninja462 You can't really unit test this as far as I am aware. What you need to do, is make a class with the functionality that is run within the closure, then unit test this. Thereafter, you just need to call the class via the scheduler and trust that the scheduler is working correctly calling it.

darkninja462's avatar

Hi @ifpingram thank you for that, I did as you said and refactored it and then tested the class/closure on its own.

Regards -Darkninja462

elgabo.msn@gmail.com's avatar

Have you tried running the scheduler manually from your unit test?

Artisan::call('schedule:run');
2 likes
rahul900day's avatar

First you need to time travel to your specific time like this

$this->travelTo('2021-01-01 00:00:00');

Then you have to run Artisan::call('schedule:run');

1 like
MattApril's avatar

A better method IMO. It does not require running the commands.

gist.github.com/MattApril/e6f4b8af32eb6438f482d307280d6a79

3 likes

Please or to participate in this conversation.