终于让我那个愚蠢简单的测试通过了,但我有一种感觉,好像做得不对。
我有一个SessionsController,负责显示登录页面和登录用户。
我决定不使用facade,这样我就不必扩展Laravel的TestCase并在单元测试中产生性能损失。因此,我通过控制器注入了所有依赖项,像这样 -
SessionsController - 构造函数
public function __construct(UserRepositoryInterface $user,
AuthManager $auth,
Redirector $redirect,
Environment $view )
{
$this->user = $user;
$this->auth = $auth;
$this->redirect = $redirect;
$this->view = $view;
}
我已经声明了必要的变量并使用了命名空间,这里不必介绍。
create方法会检测用户是否被授权,如果是,则重定向到主页,否则显示登录表单。
SessionsController - Create
public function create()
{
if ($this->auth->user()) return $this->redirect->to('/');
return $this->view->make('sessions.login');
}
现在进行测试,我对此全新,所以请谅解。
SessionsControllerTest
class SessionsControllerTest extends PHPUnit_Framework_TestCase {
public function tearDown()
{
Mockery::close();
}
public function test_logged_in_user_cannot_see_login_page()
{
# Arrange (Create mocked versions of dependencies)
$user = Mockery::mock('Glenn\Repositories\User\UserRepositoryInterface');
$authorizedUser = Mockery::mock('Illuminate\Auth\AuthManager');
$authorizedUser->shouldReceive('user')->once()->andReturn(true);
$redirect = Mockery::mock('Illuminate\Routing\Redirector');
$redirect->shouldReceive('to')->once()->andReturn('redirected to home');
$view = Mockery::mock('Illuminate\View\Environment');
# Act (Attempt to go to login page)
$session = new SessionsController($user, $authorizedUser, $redirect, $view);
$result = $session->create();
# Assert (Return to home page)
}
}
这一切都没问题,但我不想为每个SessionsControllerTest声明所有这些模拟依赖项。是否有一种方法可以在构造函数中声明这些模拟依赖项,并通过它们的变量进行调用来进行模拟?