终于让我愚蠢的简单测试通过后,我感觉我没有正确地做到这一点。Laravel使用PHPUnit和Mockery进行测试 - 在Controller上设置依赖关系test
我有一个SessionsController,这是负责显示登录页面和登录的用户。
我已经决定不使用外墙,这样我就不必延长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;
}
我已经做了必要的变量声明和使用的命名空间,这我不会在这里包括它不必要的。
创建方法检测用户是否被授权,如果他们然后我将他们重定向到主页,否则会显示登录表单。
SessionsController - 创建
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每个测试这些嘲笑依赖。有没有办法在构造函数中声明这些模仿的依赖关系?然后通过变量调用它们来模拟?
谢谢你的任何建议,并花时间来阅读我的问题。
谢谢@watcher!我很感谢你的全面回答 –
np,很高兴提供帮助 –