PHPUnit assertDatabaseHas()返回TypeError

时间:2017-05-30 00:56:12

标签: php laravel phpunit

尝试在这里测试模型,但每次尝试使用assertDatabaseHas方法时,它都会给出类型错误。 Laravel 5.4和PHPUnit 6。

    PHPUnit 6.1.4 by Sebastian Bergmann and contributors.

..E                                                                 3 / 3 (100%)

Time: 815 ms, Memory: 10.00MB

There was 1 error:

1) Tests\Unit\ModelTest::test_model_creation
TypeError: Argument 2 passed to PHPUnit\Framework\Assert::assertThat() must be an instance of PHPUnit\Framework\Constraint\Constraint, instance of Illuminate\Foundation\Testing\Constraints\HasInDatabase given, called in /home/vagrant/domains-api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php on line 22

/home/vagrant/domains-api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:22
/home/vagrant/domains-api/tests/Unit/ModelTest.php:36

ERRORS!
Tests: 3, Assertions: 2, Errors: 1.

测试类中的代码:

$this->assertDatabaseHas('domains', [
            'domain' => $domain,
            'domain_type' => 'full_domain',
        ]);

我使用laravel文档作为参考,语法似乎是正确的(至少对我而言)。 https://laravel.com/docs/5.4/database-testing#introduction

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

问题似乎是Laravel 5.4不支持在版本6中引入的PHPUnit的命名空间。

如果你比较分支,很容易看到:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Testing/Constraints/HasInDatabase.php#L8

VS

https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Testing/Constraints/HasInDatabase.php#L6-L8

我认为最好的解决方案是使用PHPUnit 5.x运行测试,或者可能更新laravel/framework以使用master。由于主人可能包含重大变化,因此第一个似乎是目前更安全的方法。