假设我有两个从 Eloquent
扩展而来的模型,它们相互关联。我可以 mock 这段关系吗?
即:
class Track extends Eloquent {
public function courses()
{
return $this->hasMany('Course');
}
}
class Course extends Eloquent {
public function track()
{
return $this->belongsTo('Track');
}
}
在 MyTest 中,我当然想创建一个模拟,并返回一个轨道实例,通过调用轨道属性,而不是轨道实例(我不想要查询 build 者)
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
}
}
最佳答案
由于 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);
关于unit-testing - laravel 4 mock 模拟模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050435/