Which is an acceptable approach for testing commands in Laravel 5.2 with PHPUnit?

删除回忆录丶 提交于 2019-11-29 15:32:37

In above case, you should remove use Artisan; because you don't use any namespace for your test

I got to an acceptable approach as follows:

<?php

use App\Console\Commands\SendBusinessReport;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Tester\CommandTester;
use Timegridio\Concierge\Models\Appointment;

class SendBusinessReportTest extends TestCase
{
    use DatabaseTransactions;
    use CreateBusiness, CreateUser, CreateContact, CreateAppointment, CreateService, CreateVacancy;

    /** @test */
    public function it_reports_to_all_businesses()
    {
        $this->arrangeFixture();

        // BEGIN Actual solution code
        $application = new ConsoleApplication();

        $testedCommand = $this->app->make(SendBusinessReport::class);
        $testedCommand->setLaravel(app());
        $application->add($testedCommand);

        $command = $application->find('business:report');

        $commandTester = new CommandTester($command);

        $commandTester->execute([
            'command' => $command->getName(),
        ]);
        // END Actual solution code

        $this->assertRegExp('/Scanning all businesses../', $commandTester->getDisplay());
    }

    /**
     * Arrange Fixture.
     *
     * @return void
     */
    protected function arrangeFixture()
    {
        $this->owner = $this->createUser();
        $this->issuer = $this->createUser();

        $this->business = $this->createBusiness();
        $this->business->owners()->save($this->owner);

        $this->contact = $this->createContact();
        $this->contact->user()->associate($this->issuer);

        $this->service = $this->makeService();
        $this->business->services()->save($this->service);

        $this->vacancy = $this->makeVacancy();
        $this->vacancy->service()->associate($this->service);

        $this->business->vacancies()->save($this->vacancy);

        $appointment = $this->makeAppointment($this->business, $this->issuer, $this->contact, [
            'status' => Appointment::STATUS_CONFIRMED,
            ]);
    }
}


alariva@trinsic ~/timegrid.io/app $ phpunit --filter=it_reports_to_all_businesses
PHPUnit 5.4.6 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 813 ms, Memory: 30.00MB

OK (1 test, 1 assertion)

Reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!