douyou8047 2013-07-17 18:49
浏览 65
已采纳

如何在Laravel 4中添加Auth作为控制器依赖项进行测试

I'm starting out with some TDD in Laravel 4. While I understand the basics of dependency injection, I can't seem to get my head around how to mock the Auth functionality. Below is my current user controller with just the index method and it's applicable test. The current setup keeps throwing me errors when I run phpunit, namely "undefined index" errors for Auth. Is there a better way of doing this?

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

User Controller Test

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

}
  • 写回答

1条回答 默认 最新

  • dongzinen1061 2013-12-18 21:23
    关注

    I've found the solution to this issue.

    All I had to do is call the be() method in my test to set the currently logged in user.

    $this->be(User::find(1));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库