Unit testing laravel 4模拟-模拟模型关系

Unit testing laravel 4模拟-模拟模型关系,unit-testing,laravel,mocking,laravel-4,mockery,Unit Testing,Laravel,Mocking,Laravel 4,Mockery,假设我有两个模型是从扩展而来的,它们相互关联。我可以嘲笑这种关系吗 即: 在MyTest中,我当然希望创建一个模拟,并通过调用track属性而不是track实例来返回track的实例(我不希望使用查询生成器) 使用\ mockry作为m; 类MyTest扩展了TestCase{ 公共功能设置() { $track=新曲目(数组('title'=>'foo'); $course=m::mock('course[track]',数组('track'=>$track)); $track=$course

假设我有两个模型是从
扩展而来的,它们相互关联。我可以嘲笑这种关系吗

即:

在MyTest中,我当然希望创建一个模拟,并通过调用track属性而不是track实例来返回track的实例(我不希望使用查询生成器)

使用\ mockry作为m;
类MyTest扩展了TestCase{
公共功能设置()
{
$track=新曲目(数组('title'=>'foo');
$course=m::mock('course[track]',数组('track'=>$track));

$track=$course->track//因为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);
模拟
课程
对象时,不需要指定
跟踪
方法,除非您也想测试依赖查询生成器的代码。如果是这种情况,则可以模拟
跟踪
方法,如下所示:

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