Assalamualaikum / Hi,
I will share how to write custom Artisan Commands with Test included.
First, create your custom command with
php artisan make:command ReloadCacheCommand. Then open up the class located at
app/Console/Commands and use the following code. Basically this command will clear all available caches in Laravel application and cache it back.
Next, register your command in
Now, open up your terminal, and run
php artisan reload:cache. You should have something like the following:
Now, Part 1, you already created custom Artisan command. The next part is to write test for your custom artisan command.
php artisan make:test ReloadCacheTest --unit to create a unit test for our custom artisan command. Once the class created, open it up — located at
Then write as following in the class:
At Line 12, we simply check if the class is exist — just my personal practice to ensure the class is exist, before proceed to other test cases.
The next part is to check either the artisan command is correctly giving the desire output.
$this->artisan('artisan:command') to call artisan command from Test.
$this->artisan('artisan:command')->expectedOutput('output in terminal') is expecting the output that should be printed when the command runs.
$this->artisan('artisan:command')->assertExitCode(0) is to assert that the command ends without error.
So this is one simple way to test your custom artisan commands — but of course you can further details how to test your artisan commands.
For me, this is good enough to make sure things run smoothly.
I’ve created a simple project for this purpose, feel free to explore — Artisan Commands with Test.