php - 如何模拟模型->保存()?
问题描述
我需要模拟一个调用函数 save() 的数据库模型。
测试
//Setup function
$this->jobAccessor = Mockery::mock(JobAccessor::class);
$this->job = Mockery::mock(Job::class);
$this->app->instance('App\Models\Job', $this->job);
$this->app->instance('App\Data\JobAccessor', $this->jobAccessor);
//testing function
$job = new Job([
'id' => 22,
'user_id' => 123
]);
$this->jobAccessor->shouldReceive('find')
->with($jobId)
->andReturns($job);
$this->job->shouldReceive('save')->once();
测试功能
$job = $this->jobAccessor->find($this->id);
//do stuff with job then save
$job->save(); //how do I mock save here?
我怎么能嘲笑$job->save();
我上面做的方式不起作用。我收到以下错误Illuminate\Database\QueryException: could not find driver
。它仍在尝试访问数据库。
解决方案
不确定,但我认为您需要将保存方法声明为:
$this->job->shouldReceive('save')->with(m::on(function ($job) use ($data) {
// set all attributes of your job Model
return
$job->id == $data['id']
&& $job->name == $data['name'];
// ....
}))
->andReturns($this->job)
->once();
推荐阅读
- powershell - powershell 调用命令到变量并写成表格
- sql-server - SQL Server:从字符串中提取 $#,###
- sql-server - TryParse SSIS 忽略源行
- git - Git 完全删除一个未合并的根节点
- python - 如何使用 Python 3 将 lzma2 (.xz) 和 zstd (.zst) 文件解压缩到文件夹中?
- ios - KVO 不适用于 Settings.bundle 值
- qt - 如何制作 9*9 地图,我可以在其中使用 Qt5.12.1 在某些网格中写入数字?
- lotus-notes - LotusNotes 从带有图像的对话框中获取用户输入的最佳方式
- git - 如何在 github 中复制最新的提交
- reactjs - 如何使用到达路由器在服务器子目录上部署 React 应用程序?