Courses

Testing in Laravel 11: Advanced Level

Testing Artisan Commands

Summary of this lesson:
- Learn how to test Artisan console commands
- Use artisan() method to run commands in tests
- Check command success and failure
- Verify command output and exit codes
- Explore different assertion methods for Artisan commands

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 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord