Laravel控制台命令测试使用选项

时间:2018-10-14 03:47:11

标签: laravel phpunit

我测试了控制台命令,但是'--forced'选项不起作用。

我认为--forced可以,因为在vendor / symfony / console / Input / InputOption.php中存在以下代码

if (0 === strpos($name, '--')) {
    $name = substr($name, 2);
}

我设置为“强制”并得到相同的结果。您能帮我吗?

控制台命令

class SendOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:send_order {mode} {template_id} {order_id?} {--forced}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send order command';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->line('');
        $this->line('===========================================');
        $this->line('Running DEFAULT task [SendOrderCommand:handle]');
        $this->line('===========================================');
        $this->line('');

        $mode = $this->argument('mode');
        $templateId = $this->argument('template_id');
        $orderId = $this->argument('order_id');
        $forced = $this->option("forced");

测试代码

class SendOrderCommandTest extends TestCase
{
    public function testSendOrderCommandSuccessRealForced()
    {
        $output = $this->execute(['mode' => 'real', 'template_id' => 1, 'order_id' => 1, '--forced']);
        $this->assertFalse(strpos(trim($output->fetch()), 'already instructed') !== false);
    }



$this->assertFalse(strpos(trim($output->fetch()), 'already instructed') !== false);

该测试预期为“ false”(结果剂量不包含“已经指示”),但结果为“ true”。

[期望]

[common] php artisan --env=local command:send_order real 10007 10002 --forced                                                                                                                                                                                                
===========================================
Running DEFAULT task [SendOrderCommand:handle]
===========================================

没有错误。

[实际]

[common] php artisan --env=local command:send_order real 10007 10002 --forced                                                                                                                                                                                            
===========================================
Running DEFAULT task [SendOrderCommand:handle]
===========================================

It's already instructed. If forcibly instructed, use the forced option. 

'-forced'选项必须跳过已经指示的内容。

也就是说,“-forced”选项不接收“ command:send_order”。

1 个答案:

答案 0 :(得分:0)

您应该在测试中使用它:

$this->artisan('command:send_order', [
   'mode' => 'value for mode',
   'template_id' => 123,
   'order_id' => 123,
   'forced' => true
];

进一步阅读: https://laravel.com/docs/7.x/console-tests