Laravel DatabaseMigrations produces error: Call to a member function call() on null

Laravel DatabaseMigrations produces error: Call to a member function call() on null

我试图在我的单元测试中 运行 DatabaseMigrations,但出现以下错误:

1) VisitStaffPagesTest::testLogBills
Error: Call to a member function call() on null

/Users/x/Documents/office/vendor/laravel/framework/src/Illuminate/Foundation/Testing/ApplicationTrait.php:312
/Users/x/Documents/office/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseMigrations.php:12

来自数据库迁移:

public function runDatabaseMigrations()
{
    $this->artisan('migrate'); // This is line 12

    $this->beforeApplicationDestroyed(function () {
        $this->artisan('migrate:rollback');
    });
}

来自 ApplicationTrait:

public function artisan($command, $parameters = [])
{
    return $this->code = $this->app['Illuminate\Contracts\Console\Kernel']->call($command, $parameters);
}

知道我为什么会收到此错误吗?

我认为你应该从

修改你的TestCase中的createApplication方法
public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    return $app;
}

至:

public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    $this->app = $app;  // line added

    return $app;
}

我最终使用 TestCase.php 文件中的这段代码解决了这个问题:

public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    $this->code = $app['Illuminate\Contracts\Console\Kernel']->call('migrate');
    $this->beforeApplicationDestroyed(function () use ($app) {
        $app['Illuminate\Contracts\Console\Kernel']->call('migrate:rollback');
    });

    return $app;
}

本质上我只是手动调用迁移和回滚。不确定为什么它有效而另一个无效。