首页 > 解决方案 > 如何模拟模型->保存()?

问题描述

我需要模拟一个调用函数 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。它仍在尝试访问数据库。

标签: phplaravelphpunit

解决方案


不确定,但我认为您需要将保存方法声明为:

$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();

推荐阅读