How To Test Artisan Commands in Laravel 5

2019-04-17 20:11发布

问题:

I build an Artisan Command to receive data from a socket, and I want to write a unit-testing for this command but I'm not sure how to write such a test.

Anyone an idea how to write it?

回答1:

It is much easier now:

<?php

class YourCommandTest extends TestCase
{

    public function testExample()
    {
        $this->artisan('command', ['param' => 'value']);
    }

}


回答2:

Example of test

<?php

class YourCommandTest extends TestCase
{
    public function testExample()
    {
        Artisan::call('your_command', [
            'command_parameter_1' => 'value1',
            'command_parameter_2' => 'value2',
        ]);

        // If you need result of console output
        $resultAsText = Artisan::output();

        $this->assertTrue(true);
    }

}


回答3:

Maybe useful for someone

Artisan command Test Cases in Laravel 5.7

public function test_console_command()
{
    $this->artisan('your_command')
         ->expectsQuestion('What is your name?', 'Ajay Makwana')
         ->expectsQuestion('Which language do you program in?', 'PHP')
         ->expectsOutput('Your name is Ajay Makwana and you program in PHP.')
         ->assertExitCode(0);
}

https://laravel-news.com/testing-artisan-commands-in-laravel-5-7