Search code examples
laravellaravel-artisan

Call to a member function expectsOutput() on integer when testing artisan console command


I have a very simple example to show the problem:

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

I get the following error:

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

I know the command definitely runs because if I put a dump statement in it shows the debug output.

I am using Laravel 6.3. Is there a different way to test this?


Solution

  • The problem I was using was that TestCase was using Laravel\BrowserKitTesting\TestCase as BaseTestCase. I ended up creating another Base just for console commands.

    <?php
    
    namespace Tests;
    
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    
    abstract class ConsoleTestCase extends BaseTestCase
    {
        use CreatesApplication;
    }