首页 > 解决方案 > 无法模拟 Laravel 模型方法

问题描述

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

我的模型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);

    }

但返回值为空。

标签: laraveltestingphpunitmockery

解决方案


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

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

推荐阅读