Paulund

Laravel Unit Testing Commands

In this tutorial we're going to learn how you can unit test your Laravel artisan commands so that you can make sure they're doing exactly what you expect them to do. When unit testing it's important to understand that you need to be able to customise the input of the command and assert that you have the desired output from the command. In Laravel you can create your own artisan commands by simply running the command php artisan make:command TestCommand. But like all the code we right we need to make sure that we can test it properly.

Artisan Facade

Laravel comes with a facade that allows you to call artisan commands from your code.


Artisan::call('command', [
    'parameter_1' => 'value1',
    'parameter_2' => 'value2',
]);

This means that we can call the command from a unit test and then use the Facade again to grab the output of the command.


$response = Artisan::output();

$this->assertEquals('Result', $response);

Putting this into a testcase will look like the below.


class UnitCommandTest extends TestCase
{
    use RefreshDatabase;

    public function testExample()
    {
        Artisan::call('command', [
            'parameter_1' => 'value1',
            'parameter_2' => 'value2',
        ]);

        // Get the output of the response
        $response = Artisan::output();

        $this->assertEquals('Result', $response);
    }
}