2015-02-10 89 views
0

我正在尝试为几个控制器操作编写phpunit测试。一切似乎都很好,除了嘲笑密码外观。嘲讽Laravel 4中的密码门面

其中一个动作(“忘记密码”)是这样的:

if (Auth::check()) 
    //return a redirect since the user is already logged in 

switch ($response = Password::remind(Input::only('email'))) 
{ 
    case Password::INVALID_USER: 
     //return a redirect with error messages 

    case Password::REMINDER_SENT: 
     //return a redirect with success message flushed 
} 

两个验证和密码是门面,默认配备了Laravel。

测试Auth::check()部分工作得很好:

Auth::shouldReceive('check')-> 
    once()-> 
    andReturn(false); //or true depending on my test case 

但是,当我尝试Password::remind()同样尝试把它不起作用:

Password::shouldReceive('remind')-> 
    once()-> 
    andReturn(Password::INVALID_USER); 

我得到“SQLSTATE访问被拒绝”异常这意味着应用程序正试图访问数据库。

我也尝试添加with(array())到我的测试,甚至绑定Mockery::mock('\Illuminate\Auth\Reminders\PasswordBroker') - 这一切都没有帮助。

如何测试此控制器的动作?为什么密码外观与Auth不同?我还应该尝试什么?

谢谢

回答

0

所以我做了一些更多的搜索,编码和调查。尽管它应该按照我第一次打算的方式工作,但我终于成功了。

我在Laravel的文档中看到,调用Facade::shouldReceive('method')应该返回一个Mockery对象。所以我在我的测试中试过这个:

var_dump(get_class(Auth::shouldReceive('check'))); 
var_dump(get_class(Password::shouldReceive('remind'))); 

第一个按预期工作,但密码不是。所以在阅读了网页之后,我走过了Laravel门面和服务提供商,终于找到了一些东西。

我嘲笑一个PasswordBroker对象(这就是密码外观指的是什么)和“介绍它”给IoC。

$this->authReminder = Mockery::mock('Illuminate\Auth\Reminders\PasswordBroker'); 
App::instance('auth.reminder', $this->authReminder); 

再后来我使用这个对象而不是密码门面是这样的:

$this->authReminder-> 
    shouldReceive('remind')-> 
    once()-> 
    andReturn(Password::INVALID_USER); 

我知道这并不能回答为什么门面嘲讽不使用密码工作,但至少要经过很多几个小时的挣扎我可以写出我需要的测试,并继续进行项目。