s.spaan's avatar
Level 41

Test Artisan Command Called

Hi, i'm looking for a way to test is a artisan command was called from a controller.

I know how to test the command itself, but how to test that the command was executed.

0 likes
5 replies
aurawindsurfing's avatar

Hi @s.spaan

Maybe simply log to file from your artisan command and watch the file from command line?

tail -f your_test_log_file
s.spaan's avatar
Level 41

@aurawindsurfing I can test if the command is executed, but i would like to do something like this:

/** @test */
public function command_was_called() 
{

Artisan::fake();

$this->post('/run-command', ['parameter' => 2]);

Artisan::assertIsCalled(SomeCommand::class);

}

Like we can do with the Queues ..

jonathanbossenger's avatar

Assuming your artisan command in your controller is something like this

$exitCode = Artisan::call('artisan-command', ['user_id' => $this->user->id]);

You can mock and swap the Artisan facade in your test

        $mock = \Mockery::mock();
        $mock->shouldReceive('call')
            ->with('artisan-command', ['user_id' => $user->id]);
        Artisan::swap($mock);
5 likes
JaroslavKlimcik's avatar
Level 2

Tested with Laravel 9 and you can do this directly:

        Artisan::shouldReceive('call')
            ->once()
            ->with(
                'command:run-command',
                [
                    'some-parameter' => $this->variable,
                ]
            );
1 like
s.spaan's avatar
Level 41

FYI: Also works in Laravel 8.83.14

Please or to participate in this conversation.