在测试时设置模型的属性


Setting attributes on models while testing

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

我尝试在模拟对象上使用andSet()设置这些属性,但这给了我一个错误getAttribute() does not exist on this mocked object..

这是我的控制器方法。

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');
}

我得到的最远的是删除处理getAttribute() does not exist on this mock objectandSet()部分,但随后它告诉我consumer加载视图时未定义并且仍然失败。

你应该改变:

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

对此:

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