laravel - 无法模拟 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);
}
但返回值为空。
解决方案
您应该从容器中检索模拟实例
$mockedModel = app()->make(StoreModel::class);
推荐阅读
- c# - 生成具有多个中心点的径向渐变
- sql-server - 使用 DBATOOLS 更新 SQL Server 中的表
- selenium - 无法打开与“会话”消息总线的连接:无法在没有 $DISPLAY 的 X11 的情况下自动启动 dbus-daemon
- xml - XMLStream Reader Scala - END_DOCUMENT 的正确句柄
- amazon-web-services - Amazon EC2 中子域的 HTTPS 设置
- python - 将 json 数据集翻译成不同的自然语言
- vim - 如何设置 Nord VIM 配色方案?
- python - 从熊猫数据框中的文本替换unicode
- c++ - Visual Studio 如何将多个 C++ 文件编译在一起?
- nullpointerexception - 从 Room 创建的对象导致 NullPointerException