【问题标题】:Not able to mock Laravel Model method无法模拟 Laravel 模型方法
【发布时间】:2020-09-11 08:41:28
【问题描述】:

我目前正在编写一个测试来测试模型方法。

我的模型Store有这个方法:

public function hourTemplate() {
    return $this->belongsTo(HourTemplate::class);
}

我在 setUp 方法中也对这段代码进行了测试:

public function setUp() : void
    {
        parent::setUp();

        $this->storeMock = Mockery::mock(StoreModel::class)->makePartial();
        app()->instance(StoreModel::class, $this->storeMock);
    }

而测试方法是这样的:

    public function test_getStoreHoursArray_when_hour_isNull() {
        $this->storeMock->shouldReceive('hourTemplate')->andReturn(new HourTemplate());

        dump((new StoreModel())->hourTemplate);

    }

但是返回值为null。

【问题讨论】:

    标签: laravel testing phpunit mockery


    【解决方案1】:

    您应该从容器中检索模拟实例

    $mockedModel = app()->make(StoreModel::class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 2021-10-21
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多