php – 在测试时设置模型的属性

我试图测试一个控制器,并嘲笑模型.在加载视图之前,一切似乎都很顺利,它无法检索应该通过关系加载的视图上的属性.

我已经尝试在模拟对象上使用andSet()设置这些属性,但是这给了我一个错误getAttribute()在这个模拟对象上不存在.

这是我的控制器方法.

public function __construct(ApplicationRepositoryInterface $application)
{
    $this->beforeFilter('consumer_application');

    $this->application = $application;
}

public function edit($application_id)
{
    $application = $this->application->find($application_id);

    $is_consumer = Auth::user()->isAdmin() ? 'false' : 'true';

    return View::make('application.edit')
        ->with('application', $application)
        ->with('is_consumer', $is_consumer)
        ->with('consumer', $application->consumer);
}

而我的测试……

public function setUp()
{
    parent::setUp();
    $this->mock = Mockery::mock($this->app->make('ApplicationRepositoryInterface'));
}

public function testEdit()
{
    $this->app->instance('ApplicationRepositoryInterface', $this->mock);

    $this->mock
        ->shouldReceive('find')
        ->once()
        ->andReturn(Mockery::mock('Application'))
        ->andSet('consumer', Mockery::mock('Consumer'));

    Auth::shouldReceive('user')
        ->once()
        ->andReturn(Mockery::mock(array('isAdmin' => 'true')));

    $application_id = Application::first()->id;
    $this->call('GET', 'consumer/application/'.$application_id.'/edit');

    $this->assertResponseOk();
    $this->assertViewHas('application');
    $this->assertViewHas('is_consumer');
    $this->assertViewHas('consumer');
}

我得到的最远的是删除了andSet()部分,该部分负责处理此模拟对象上不存在的getAttribute(),但它告诉我在加载视图时仍然未能定义使用者.

最佳答案 你应该改变:

 Auth::shouldReceive('user')
    ->once()
    ->andReturn(Mockery::mock(array('isAdmin' => 'true')));

对此:

 Auth::shouldReceive('user->isAdmin')
    ->once()
    ->andReturn('true');
点赞