【问题标题】:laravel testable store method with validation in basemodel在 basemodel 中进行验证的 laravel 可测试存储方法
【发布时间】:2013-07-28 15:17:56
【问题描述】:

我正在尝试创建一个追随者,但是,因为我正在调用 Auth::user()->id 我收到错误“尝试获取非对象的属性”。目前我一直在构建一个输入数组,当我运行 create 方法时,验证是从 BaseModel 中的引导方法触发的。有什么方法可以模拟 $input 数组,还是应该在存储库的 create 方法中进行验证?

<?php

class FollowersTest extends TestCase {

public function setUp()
{
  parent::setUp();

  $this->mock = $this->mock('Convoconnect\Storage\Follower\FollowerRepository');
}

public function mock($class)
{
  $mock = Mockery::mock($class);

  $this->app->instance($class, $mock);

  return $mock;
}

public function tearDown()
{
  Mockery::close();
}

/**
 * Test Store success
 */
public function testStoreSuccess()
{
  $input = [
    'user_id' => 1,
    'follower_id' => 4,
  ];

    $this->mock
        ->shouldReceive('create')
        ->once();

  $this->call('POST', 'followers', $input);

  $this->assertRedirectedToRoute('followers.index');
 }
}



<?php

use Convoconnect\Storage\Follower\FollowerRepository as Follower;

class FollowersController extends BaseController {

/**
* Follower Repository
*
* @var Follower
*/
protected $follower;

public function __construct(Follower $follower) {
    $this->follower = $follower;
}

public function store() {

    $input = [
        'user_id' => Auth::user()->id,
        'follower_id' => Input::get('follower_id'),
    ];

    $follower = $this->follower->create($input);

    if($follower->save()) return Redirect::route('followers.index');

    return Redirect::back()
        ->withInput()
        ->withErrors($follower->errors);
 }
}   

【问题讨论】:

    标签: unit-testing tdd phpunit laravel laravel-4


    【解决方案1】:

    您可以模拟 Validator 行为:

    Validator::shouldReceive('make')
        ->once()
        ->andReturn(Mockery::mock(array('fails' => true)));
    

    this Nettuts article 中有很多关于测试控制器的有用信息。 Jeffrey Way 的书,Laravel Testing Decoded,也很值得一看。

    【讨论】:

    • 我的问题是我的测试失败了,因为我正在调用 Auth::user()->id 来构建我的输入,所以我收到错误“尝试获取非对象的属性”
    • Laravel 包含 a test helper method 来设置当前认证的用户。
    猜你喜欢
    • 2016-10-19
    • 2018-10-23
    • 2013-07-31
    • 2021-03-16
    • 2017-01-30
    • 2019-07-05
    • 2014-09-04
    • 2018-01-29
    • 2013-12-29
    相关资源
    最近更新 更多