【问题标题】:Setting attributes on models while testing测试时在模型上设置属性
【发布时间】:2015-02-17 17:24:22
【问题描述】:

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

我尝试在模拟对象上使用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');
}

我得到的最远的是删除 andSet() 部分,该部分负责处理 getAttribute() does not exist on this mock object 但它告诉我 consumer 在视图加载但仍然失败时未定义。

【问题讨论】:

    标签: php laravel phpunit mockery


    【解决方案1】:

    你应该改变:

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

    到这里:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多