如何在Laravel 5中测试Artisan命令

40

我编写了一个Artisan命令,用于从套接字接收数据,现在想为该命令编写单元测试,但不确定如何编写测试。

有没有任何想法可以帮助我编写这个测试?


1
请返回以下内容的翻译文本:http://laravel.com/docs/master/artisan#calling-commands-via-code - andrewtweber
https://dev59.com/gVsW5IYBdhLWcg3wk4DM - bernie
这对我来说是更好的方法:https://dev59.com/1Znga4cB1Zd3GeqPVjxl#41122816 - Ryan
3个回答

47

测试示例

<?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
发现这种方法对于验收测试来说简单而有用。然而,它不会为命令本身注册代码覆盖率。 - alariva
1
我使用选项 --coverage-html 运行测试以生成覆盖率报告:phpunit --coverage-html coverage_path。我可以看到命令内调用的方法的覆盖率。 - Nick
1
@alariva,我们的phpunit和laravel版本是相同的。我认为问题可能出在phpunit.xml的设置上。 - Nick
1
我注意到我的测试用例中有一些工作尚未完成。但是我相信你所说的方法是有效的。谢谢你的提示。我会更新一次,以覆盖那些缺失的行。 - alariva
1
刚刚测试了一下,它确实注册了代码覆盖率。谢谢。 - Manuel Azar
显示剩余5条评论

29

现在容易多了:

<?php

class YourCommandTest extends TestCase
{

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

}

8
你的主张在哪里?你为什么要做出主张? - Dr. House
这完全取决于您想要发生什么。在 $this->artisan() 调用之前会有一些设置,之后是断言。 - André Castelo
@Mkey 我的使用情况是在 $this->artisan 之前使用工厂创建 X 个数据库记录,然后在我断言 X 个作业已排队之后。 - Carlton
我正在尝试使用相同的方法,$this->artisan('custom:command CA')->expectsOutput('Searching')。但是我收到了一个错误Call to a member function expectsOutput() on int - commadelimited

8

也许对某些人有用

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接