Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Testing Artisan Commands

Premium
2 min read

I want to demonstrate how to test Artisan commands and their results, outputs, or errors.


The Artisan Command

Imagine you have an Artisan command called php artisan product:publish, which takes the product ID as a parameter.

It only publishes the product by setting the published_at to now(). But it also checks if the product is found and whether it's published already. In those cases, it throws errors.

How do we test and simulate that from our tests?

use App\Models\Product;
use Illuminate\Console\Command;
 
class ProductPublishCommand extends Command
{
protected $signature = 'product:publish {id : ID of the product to publish}';
 
protected $description = 'Publishes the product';
 
public function handle(): void
{
$product = Product::find($this->argument('id'));
 
if (!$product) {
$this->fail('Product not found');
}
 
if ($product->published_at) {
$this->fail('Product is already published');
}
 
$product->update(['published_at' => now()]);
$this->components->success('Product published');
}
}

The Tests

In the test, you can run...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…