Testing 身份验证测试运行异常
我刚刚尝试为Testing 身份验证测试运行异常,testing,laravel,phpunit,mockery,laravel-testing,Testing,Laravel,Phpunit,Mockery,Laravel Testing,我刚刚尝试为Auth编写一个简单的测试: use Mockery as m; ... public function testHomeWhenUserIsNotAuthenticatedThenRedirectToWelcome() { $auth = m::mock('Illuminate\Auth\AuthManager'); $auth->shouldReceive('guest')->once()->andReturn(true); $th
Auth
编写一个简单的测试:
use Mockery as m;
...
public function testHomeWhenUserIsNotAuthenticatedThenRedirectToWelcome() {
$auth = m::mock('Illuminate\Auth\AuthManager');
$auth->shouldReceive('guest')->once()->andReturn(true);
$this->call('GET', '/');
$this->assertRedirectedToRoute('general.welcome');
}
public function testHomeWhenUserIsAuthenticatedThenRedirectToDashboard() {
$auth = m::mock('Illuminate\Auth\AuthManager');
$auth->shouldReceive('guest')->once()->andReturn(false);
$this->call('GET', '/');
$this->assertRedirectedToRoute('dashboard.overview');
}
代码如下:
public function getHome() {
if(Auth::guest()) {
return Redirect::route('general.welcome');
}
return Redirect::route('dashboard.overview');
}
当我运行时,出现以下错误:
EF.....
Time: 265 ms, Memory: 13.00Mb
There was 1 error:
1) PagesControllerTest::testHomeWhenUserIsNotAuthenticatedThenRedirectToWelcome
Mockery\Exception\InvalidCountException: Method guest() from Mockery_0_Illuminate_Auth_AuthManager should be called
exactly 1 times but called 0 times.
—
There was 1 failure:
1) PagesControllerTest::testHomeWhenUserIsAuthenticatedThenRedirectToDashboard
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/dashboard/overview'
+'http://localhost/welcome'
我的问题是:
Auth::guest()
,而第二个似乎被调用mockry
来模拟AuthManager
,但是如果我使用facadeAuth::shoudReceive()->once()->andReturn()
,那么它最终会工作。这里的mocky
和Auth::mock
facade之间有什么不同吗谢谢。您实际上是在模拟
照亮\Auth\AuthManager
的一个新实例,而不是访问函数getHome()正在使用的验证外观。因此,你的模拟实例永远不会被调用。(以下代码均未经测试的标准免责声明。)
试试这个:
public function testHomeWhenUserIsNotAuthenticatedThenRedirectToWelcome() {
Auth::shouldReceive('guest')->once()->andReturn(true);
$this->call('GET', '/');
$this->assertRedirectedToRoute('general.welcome');
}
public function testHomeWhenUserIsAuthenticatedThenRedirectToDashboard() {
Auth::shouldReceive('guest')->once()->andReturn(false);
$this->call('GET', '/');
$this->assertRedirectedToRoute('dashboard.overview');
}
如果您查看illumb\Support\Facades\Facade
,您将看到它为您提供了模拟功能。如果您真的想按照您正在做的方式来做(创建Auth的mock实例的实例),那么您必须以某种方式将其注入测试代码中。我相信,如果您从laravel提供的TestCase类进行扩展,那么可以使用类似这样的方法来实现:
public function testHomeWhenUserIsNotAuthenticatedThenRedirectToWelcome() {
$this->app['auth'] = $auth = m::mock('Illuminate\Auth\AuthManager');
// above line will swap out the 'auth' facade with your facade.
$auth->shouldReceive('guest')->once()->andReturn(true);
$this->call('GET', '/');
$this->assertRedirectedToRoute('general.welcome');
}
我刚刚搞错了,没有创建mock对象$this->app->instance()
。无论如何,谢谢:)另外,如果您在路径上设置了->middleware(“auth”)
设置,请确保将此特性添加到测试illighted\Foundation\Testing\without middleware