2

我从 Laravel 4 中的一些 TDD 开始。虽然我了解依赖注入的基础知识,但我似乎无法理解如何模拟 Auth 功能。下面是我当前的用户控制器,只有 index 方法和适用的测试。当我运行 phpunit 时,当前设置不断向我抛出错误,即 Auth 的“未定义索引”错误。有没有更好的方法来做到这一点?

我的控制器:

class UserController extends \BaseController {

    /**
     * User instance
     * 
     * @var User
     */
    protected $user;

    /**
     * The master layout that View's will be built upon.
     * 
     * @var string
     */
    protected $layout = 'layout.user-master';

    /**
     * Constructor
     * 
     * @param User $user
     * @param View $view
     */
    public function __construct(User $user) 
    {
        $this->user = $user;

        // Filters
        $this->beforeFilter('csrf', array('on' => 'post'));
        $this->beforeFilter('auth', array('except' => array('create', 'store')));
    }

    /**
     * Display a listing of the user.
     *
     * @return Response
     */
    public function index()
    {
        $id = Auth::user()->id;

        $user = $this->user->find($id);

        $this->layout->content = View::make('user.index', compact('user'));
    }
}

用户控制器测试

<?php

use \Mockery;

class UserControllerTest extends TestCase {

    public function __construct()
    {
        // Mock an Eloquent User Model instance
        $this->mock = Mockery::mock('Eloquent', 'User');    
    }

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

    public function testIndex()
    {
        Auth::shouldReceive('user')->once()->andReturn(Mockery::any());

        $this->mock
                ->shouldReceive('find')
                ->once()
                ->with(Mockery::any())
                ->andReturn('foo');

        $this->app->instance('User', $this->mock);

        $this->call('GET', 'user');

        $this->assertViewHas('user');
    }

}
4

1 回答 1

5

我找到了解决这个问题的方法。

我所要做的就是be()在我的测试中调用该方法来设置当前登录的用户。

$this->be(User::find(1));
于 2013-12-18T21:23:48.377 回答