Jas*_*nNZ 2 php tdd unit-testing laravel laravel-4
我首先从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'));
}
}
Run Code Online (Sandbox Code Playgroud)
用户控制器测试
<?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');
}
}
Run Code Online (Sandbox Code Playgroud)
我已经找到解决此问题的方法。
我要做的就是be()在测试中调用该方法来设置当前登录的用户。
$this->be(User::find(1));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |