简体   繁体   English

laravel 4嘲弄模拟模型关系

[英]laravel 4 mockery mock model relationships

say I have two models that extend from Eloquent and they relate to each other. 说我有两个从Eloquent延伸的模型,它们彼此相关。 Can I mock the relationship? 我可以嘲笑这段关系吗?

ie: 即:

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

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

in MyTest, I want to create a mock of course, and return an instance of track, by calling the track property, not the track instance ( I don't want the query builder ) 在MyTest中,我想创建一个模拟当然,并通过调用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
    }
}

Since track is a property and not a method, when creating the mock you will need to override the setAttribute and getAttribute methods of the model. 由于track是属性而不是方法,因此在创建模拟时,您需要覆盖模型的setAttributegetAttribute方法。 Below is a solution that will let you set up an expectation for the property you're looking for: 以下是一个解决方案,可让您设置您正在寻找的房产的期望:

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

You don't need to specify the track method when mocking the Course object, unless you are also wanting to test code that relies on the query builder. 除非您还想测试依赖于查询构建器的代码,否则在模拟Course对象时不需要指定track方法。 If this is the case, then you can mock the track method like this: 如果是这种情况,那么你可以像这样模拟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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM