如何在Laravel 5中测试工匠命令

32 unit-testing laravel laravel-5.1

我建立了一个Artisan命令来接收来自套接字的数据,我想为这个命令编写一个单元测试,但我不知道如何编写这样的测试.

有人知道怎么写吗?

mnv*_*mnv 43

测试示例

<?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);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 发现此方法对于验收测试非常简单且有用。但是,它不会为命令本身注册代码覆盖率。 (2认同)

Rom*_*ush 27

现在要容易得多:

<?php

class YourCommandTest extends TestCase
{

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

}
Run Code Online (Sandbox Code Playgroud)

  • 你的主张在哪里?你主张什么? (2认同)

小智 7

也许对某人有用

Laravel 5.7 中的 Artisan 命令测试用例

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);
}
Run Code Online (Sandbox Code Playgroud)

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