laravel 4 嘲弄模拟模型关系
Posted
技术标签:
【中文标题】laravel 4 嘲弄模拟模型关系【英文标题】:laravel 4 mockery mock model relationships 【发布时间】:2014-01-29 18:53:46 【问题描述】:假设我有两个从 Eloquent
扩展而来的模型,它们相互关联。我可以嘲笑这段关系吗?
即:
class Track extends Eloquent
public function courses()
return $this->hasMany('Course');
class Course extends Eloquent
public function track()
return $this->belongsTo('Track');
在 MyTest 中,我当然想创建一个 mock,并返回一个 track 实例,通过调用 track 属性,而不是 track 实例(我不想要查询建设者)
use \Mockery as m;
class MyTest extends TestCase
public function setUp()
$track = new Track(array('title' => 'foo'));
$course = m::mock('Course[track]', array('track' => $track));
$track = $course->track // <-- This should return my track object
【问题讨论】:
【参考方案1】:由于 track 是属性而非方法,因此在创建模拟时,您需要覆盖模型的 setAttribute
和 getAttribute
方法。下面是一个解决方案,可让您为您正在寻找的财产设定期望:
$track = new Track(array('title' => 'foo'));
$course = m::mock('Course[setAttribute,getAttribute]');
// You don't really care what's returned from setAttribute
$course->shouldReceive('setAttribute');
// But tell getAttribute to return $track whenever 'track' is passed in
$course->shouldReceive('getAttribute')->with('track')->andReturn($track);
在模拟Course
对象时,您不需要指定track
方法,除非您还想测试依赖于查询生成器的代码。如果是这种情况,那么您可以像这样模拟 track
方法:
// This is just a bare mock object that will return your track back
// whenever you ask for anything. Replace 'get' with whatever method
// your code uses to access the relationship (e.g. 'first')
$relationship = m::mock();
$relationship->shouldReceive('get')->andReturn([ $track ]);
$course = m::mock('Course[track]');
$course->shouldReceive('track')->andReturn($relationship);
【讨论】:
以上是关于laravel 4 嘲弄模拟模型关系的主要内容,如果未能解决你的问题,请参考以下文章