Laravel 5.6单元测试在null上调用成员函数beginTransaction()

时间:2018-03-16 12:33:53

标签: php mongodb laravel phpunit laravel-5.6

我有一个运行5.6版本的Laravel项目。 连接的数据库是mongodb和jenssegers / mongodb包。

我写了一个Unittest来测试与用户相关的功能。

该测试在配置的测试mongodb数据库中创建新用户。 我希望在每次测试运行后刷新数据库,因此我使用RefreshDatabase Trait。

使用RefreshDatabase Trait时,运行测试时出现以下错误:

  

有1个错误:

     

1)测试\ Unit \ UserTest :: it_gets_top_user       错误:在null

上调用成员函数beginTransaction()

当不使用Trait时,测试会在数据库中创建所有必要的东西,并在没有错误的情况下执行断言。

测试如下:

/** @test */
public function it_gets_top_user()
{
    factory(\App\Users\User::class, 5)->create();

    $userOne = factory(\App\Users\User::class)->create([
        'growth' => 10
    ]);

    $topUser = Users::getTopUser();

    $collection = new Collection();

    $collection->push($userOne);


    $this->assertEquals($collection, $topUser);
} 

我在composer.json中使用以下版本:

"laravel/framework": "5.6.*",
"jenssegers/mongodb": "3.4.*",
"phpunit/phpunit": "~7.0",

服务器上使用以下版本:

  • PHP 7.2
  • MongoDB 3.4
  • PHP MongoDB Extension 1.4.2

我使用安装在供应商目录中的phpunit调用测试:

vendor/phpunit/phpunit/phpunit

1 个答案:

答案 0 :(得分:2)

问题似乎是,RefreshDatabase Trait对于MongoDB环境根本不起作用。

我通过在Laravel项目的RefreshDatabase目录中创建自己的testing/ Trait来解决上述问题。

Trait看起来像这样:

<?php

namespace Tests;

trait RefreshDatabase
{
    /**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
    public function refreshDatabase()
    {
        $this->dropAllCollections();
    }

    /**
     * Drop all collections of the testing database.
     *
     * @return void
     */
    public function dropAllCollections()
    {
        $database = $this->app->make('db');

        $this->beforeApplicationDestroyed(function () use ($database) {
            // list all collections here
            $database->dropCollection('users');
        });
    }
}

要启用此特征,我已覆盖setUpTraits类中的TestCase函数。它现在看起来像这样:

/**
 * Boot the testing helper traits.
 *
 * @return array
 */
protected function setUpTraits()
{
    $uses = array_flip(class_uses_recursive(static::class));

    if (isset($uses[\Tests\RefreshDatabase::class])) {
        $this->refreshDatabase();
    }

    if (isset($uses[DatabaseMigrations::class])) {
        $this->runDatabaseMigrations();
    }

    if (isset($uses[DatabaseTransactions::class])) {
        $this->beginDatabaseTransaction();
    }

    if (isset($uses[WithoutMiddleware::class])) {
        $this->disableMiddlewareForAllTests();
    }

    if (isset($uses[WithoutEvents::class])) {
        $this->disableEventsForAllTests();
    }

    if (isset($uses[WithFaker::class])) {
        $this->setUpFaker();
    }

    return $uses;
}

最后在我的所有测试课程中,我可以使用我新创建的Trait:

<?php

namespace Tests\Unit;

use Illuminate\Database\Eloquent\Collection;
use Tests\RefreshDatabase;
use Tests\TestCase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    // tests happen here
}