【问题标题】:laravel 4 mockery mock model relationshipslaravel 4 嘲弄模拟模型关系
【发布时间】: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
    }
}

【问题讨论】:

    标签: unit-testing laravel mocking laravel-4 mockery


    【解决方案1】:

    由于 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);
    

    在模拟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);
    

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 2018-04-05
      • 2017-12-27
      • 2020-09-14
      • 2019-06-26
      • 2018-05-25
      • 2015-06-21
      • 2015-07-17
      • 2019-04-20
      相关资源
      最近更新 更多