在测试artisan控制台命令时,调用整数的成员函数ExpectsOutput()

我有一个非常简单的示例来说明问题:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class VendorCounts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vendor:counts
                            {year : The year of vendor counts}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Runs vendor counts';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Starting Vendor Counts');
    }
}
<?php

namespace Tests\Feature\Console\Vendor;

use Tests\TestCase;

class VendorCountsTest extends TestCase {

    public function testVendorCounts()
    {
        $this->artisan('vendor:counts',['year' => 2019])
             ->expectsoutput('Starting Vendor Counts')
             ->assertExitCode(0);
    }
}

我收到以下错误:

1) Tests\Feature\Console\Vendor\VendorCountsTest::testVendorCounts
Error: Call to a member function expectsoutput() on integer

/Users/albertski/Sites/vrs/tests/Feature/Console/Vendor/VendorCountsTest.php:12

我知道命令肯定会运行,因为如果我在其中添加转储语句,则会显示调试输出。

我正在使用Laravel 6.3。有其他测试方法吗?

chenga1972 回答:在测试artisan控制台命令时,调用整数的成员函数ExpectsOutput()

您可以将其添加到您的VendorCountsTest类中吗?

public $mockConsoleOutput = true;

这是由特征设置的,但是只是要确保没有改变值。当$mockConsoleOutputfalse时,它将直接运行工匠命令。当它为true时,会将其包装在一个PendingCommand对象中,该对象包含您要尝试调用的方法。

,

我使用的问题是TestCase使用Laravel\BrowserKitTesting\TestCase作为BaseTestCase。我最终只为控制台命令创建了另一个Base。

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class ConsoleTestCase extends BaseTestCase
{
    use CreatesApplication;
}
,

我遇到一个问题,即在工匠类上始终无法使用expectedOutput(),这是因为我在一个工匠类中使用了exit()和/或die()方法,实际上无法与phpunit测试方法一起很好地工作。

因此,如果您想在某个时候停止处理“脚本”,请使用空的return而不是exit()die()(如果要使用内置的{ {1}}在Laravel中进行测试。

工作示例:

->artisan()

非工作示例:

<?php
// app/Console/Commands/FooCommand.php
public function handle()
{
  $file = $this->argument('file');
  
  if (! file_exists($file)) {
    $this->line('Error! File does not exist!');
    return;
  }
}

// tests/Feature/FooCommandTest.php
public function testFoo() {
  $this->artisan('foo',['file' => 'foo.txt'])->expectsOutput('Something');
}
本文链接:https://www.f2er.com/3156628.html

大家都在问