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...