【问题标题】:Mocking Laravel Eloquent models - Mocking model that is used in AppServiceProviderMocking Laravel Eloquent models - 在 AppServiceProvider 中使用的 Mocking 模型
【发布时间】:2018-09-04 11:58:52
【问题描述】:

我正在尝试使用 alias 指令来模拟一个雄辩的模型,如下所示:

$transporter = \Mockery::mock('alias:' . Transporter::class)

我在类中添加了以下注释

* @runTestsInSeparateProcesses
* @preserveGlobalState disabled

问题是在我的AppServiceProvider.php 我注册了我的观察者:

Transporter::observe(DefaultValuesObserver::class);

因此,当我注释掉这一行时,模拟效果很好。 但是当这条线出现时,我得到一个Mockery\Exception\RuntimeException: Could not load mock App\Models\Laravel\Transporter, class already exists * 这是 phpunit 的过滤运行,只运行一个类。

我想当调用observe时,它已经在自动加载传输类了。

因此,即使在单独的进程中运行所有内容,该类也已在 AppServiceProvider 中注册。

我目前的解决方法是不使用别名,而是使用 passthru 来克服 Eloquent 问题:

$transporter = \Mockery::mock(Transporter::class)
            ->shouldReceive('getAttribute')
            ->passthru()
            ->shouldReceive('setAttribute')
            ->passthru();

但如果我必须在任何地方都这样做,这不是最好的解决方案。

【问题讨论】:

    标签: php laravel unit-testing mockery


    【解决方案1】:

    尝试使用$mock = \Mockery::mock('overload:MyClass');

    供参考http://docs.mockery.io/en/latest/reference/creating_test_doubles.html?highlight=alias%3A#overloading

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多