Make Laravel Commands Easier to Test with expectsOutput()
Suppose you have an Artisan command:
$this->info('Import completed successfully.');
The command works.
But how do you make sure someone doesn't accidentally change or remove that message later?
You can test the command output.
Create the Test
Laravel lets you call an Artisan command from a test:
$this->artisan('products:import');
You can then expect specific output:
$this->artisan('products:import')
->expectsOutput('Import completed successfully.')
->assertExitCode(0);
Now the test verifies both:
- The expected message was displayed
- The command completed successfully
Test Error Messages Too
Suppose your command displays:
$this->error('Import failed.');
You can test it:
$this->artisan('products:import')
->expectsOutput('Import failed.')
->assertExitCode(1);
This makes your command behavior explicit.