php - 如何添加 Auth 作为 Controller 依赖项以在 Laravel 4 中进行测试

标签 php unit-testing laravel tdd laravel-4

我开始在 Laravel 4 中进行一些 TDD。虽然我了解依赖注入(inject)的基础知识,但我似乎无法理解如何模拟 Auth 功能。下面是我当前的用户 Controller ,仅包含索引方法及其适用的测试。当我运行 phpunit 时,当前的设置不断抛出错误,即 Auth 的“未定义索引”错误。有更好的方法吗?

我的 Controller :

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

用户 Controller 测试

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

}

最佳答案

我已经找到了这个问题的解决方案。

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

$this->be(User::find(1));

关于php - 如何添加 Auth 作为 Controller 依赖项以在 Laravel 4 中进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707871/

相关文章:

php - 我在哪里可以获得 PHP 7 的 php-mcrypt?

reactjs - enzyme 和 Jest : How to simulate/test material-ui dropzone onChange handler when dropzone component is third party module?

multithreading - Delphi - 未创建自定义线程

php - Laravel,如何忽略访问器

php - 我们可以在 controller laravel 中使用 helper 吗?

php - 如何停止从查询中选择的表中的循环?

php - 隐私设置的数据库模式设计

php - codeigniter 在 Controller 末尾加载 View

unit-testing - 在单元测试期间禁用 log4j 输出

javascript - 模态 Bootstrap 显示在所有窗口中,这是同一封电子邮件