【问题标题】:How To Test Artisan Commands in Laravel 5如何在 Laravel 5 中测试 Artisan 命令
【发布时间】:2023-04-02 21:57:02
【问题描述】:

我构建了一个 Artisan 命令来从套接字接收数据,我想为此命令编写一个单元测试,但我不确定如何编写这样的测试。

有人知道怎么写吗?

【问题讨论】:

标签: laravel unit-testing laravel-5.1


【解决方案1】:

测试示例

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

}

【讨论】:

  • 发现这种方法对验收测试简单而有用。但是,它不会为命令本身注册代码覆盖率。
  • 我使用选项 --coverage-html 运行测试以生成覆盖率报告:phpunit --coverage-html coverage_path。而且我看到了所谓内部命令的方法的覆盖范围。
  • @alariva,我们有相同版本的 phpunit 和 laravel。我认为,问题可能出在phpunit.xml 中的设置上。
  • 我没有选项processUncoveredFilesFromWhitelist="true"
  • 我注意到我的测试用例中有一些待处理的工作。但我相信这种方法正如你所说的那样工作得很好。谢谢提示。一旦我重新查到这些缺失的行,我会更新。
【解决方案2】:

现在容易多了:

<?php

class YourCommandTest extends TestCase
{

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

}

【讨论】:

  • 你的断言在哪里?你主张什么?
  • 这完全取决于你想要发生什么。在$this-&gt;artisan() 调用之前会有一个设置,之后是断言。
  • @Mkey 我的用例是在 $this->artisan 之前使用工厂创建 X DB 记录。然后在我断言 X 作业排队之后。
  • 我正在尝试使用相同的方法,$this-&gt;artisan('custom:command CA')-&gt;expectsOutput('Searching')。但我收到一个错误Call to a member function expectsOutput() on int
【解决方案3】:

可能对某人有用

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

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 2016-09-11
    • 2019-11-13
    • 1970-01-01
    • 2015-04-14
    • 2014-03-21
    • 2014-04-01
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多