php - Laravel 5.1 测试环境中的 Eloquent 模型事件

标签 php unit-testing phpunit eloquent laravel-5

我有一个 Eloquent我在模型的 boot() 中定义了一些观察者方法的模型方法。这是一个非常简单的逻辑 - 我使用 creating()如果在调用 Model::create([...]) 时尚未定义属性,则为属性定义默认值的静态方法.

protected static function boot()
{
    parent::boot();
    static::creating(function (Content $content) {
        static::setDefaultValues($content);
    });
}

protected static function setDefaultValues(Content $content)
{
    if ( ! $content->published_at) {
        $content->published_at = Carbon::now();
    }
}

通过浏览器或控制台使用应用程序时一切正常 artisan tinker ,或数据库播种机。

但是,当我在测试用例运行时尝试使用相同的数据库种子设定逻辑通过 artisan 命令引导测试数据库时,我收到异常抛出说特定属性不能为 NULL。我对 Laravel 代码做了一些研究和挖掘,发现事件调度程序应该正常运行,因为我没有模拟任何事件,也没有使用 withoutEvents()。 helper 。

此外,全局范围似乎没有在测试环境中正确应用。

我已将 var_dumps 放置在几个关键点上(在调用 creating() 之后,在 Eloquent\Model 方法中的 save() 类中,以及在触发模型事件之后)检查属性并注意到观察者方法 正在被执行,但效果就好像模型实例不是通过引用传递给事件处理程序,而是被克隆。相同的代码在开发环境中运行正常,但在测试环境中失败。

有人遇到过这种情况吗?我不太确定如何进行,因此非常欢迎任何建议。

就其值(value)而言,我在开发中使用 MySQL 并尝试在 SQLite 数据库中运行测试以便于使用。这些测试正在使用 Laravel 开箱即用的 PHPUnit 测试设置运行。

最佳答案

将所有模型事件绑定(bind)的声明移动到 AppServiceProvider::boot() 方法,如下所示

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \App\Content::creating(function (Content $content) {
            $content::setDefaultValues($content); // change to public
        });

        // other bindings
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

关注http://laravel.com/docs/5.1/eloquent#events

您也可以使用该方法来附加模型观察者。

关于php - Laravel 5.1 测试环境中的 Eloquent 模型事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31542446/

相关文章:

php - __destruct 有多可靠?

php - 使用 GWT 优于 PHP 的优势

angularjs - 在 ionic 单元测试中广播意外的 $locationChangeStart 和 $locationChangeSuccess 事件

PHPUnit 错误 "undefined index : HTTP_HOST"

php - 如何在 Mac OS X 10.5 上不使用 PEAR 安装 PHPUnit?

php - PHP 中跨 HTTP 和 HTTPS 的 Cookie

ios - Xcode 4.5.1 中的 “File not found” , “linker command failed with exit code 1”

unit-testing - Dart pub构建:dart版本和已编译js版本之间的一致性

PHPUnit RabbitMQ : write test for create connection function

php - 将带有数字键的数组转换为对象