3

假设我有两个模型,Eloquent它们相互关联。我可以嘲笑这种关系吗?

IE:

class Track extends Eloquent {
    public function courses()
    {
        return $this->hasMany('Course');
    }
}

class Course extends Eloquent {
    public function track()
    {
        return $this->belongsTo('Track');
    }
}

在 MyTest 中,我当然想创建一个模拟,并通过调用 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
    }
}
4

1 回答 1

7

由于 track 是属性而不是方法,因此在创建模拟时,您需要覆盖模型的setAttributegetAttribute方法。以下是一个解决方案,可让您为您正在寻找的房产设定期望:

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

模拟对象时不需要指定track方法Course,除非您还想测试依赖于查询生成器的代码。如果是这种情况,那么您可以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);
于 2014-02-10T21:34:52.010 回答