我刚刚尝试为以下内容编写一个简单的测试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()
没有被调用,而第二个似乎被调用。在第二个测试用例中,为什么会失败?
有没有办法为我上面的代码编写更好的测试?甚至更好的代码来测试。
在上面的测试用例中,我
Mockery
用来模拟AuthManager
,但是如果我使用外观Auth::shoudReceive()->once()->andReturn()
,那么它最终会起作用。Mockery
这里和Auth::mock
门面有什么不同吗?
谢谢。