0

我刚刚尝试为以下内容编写一个简单的测试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'

我的问题是:

  1. 两个相似的测试用例,但为什么错误输出不同?第一个模拟Auth::guest()没有被调用,而第二个似乎被调用。

  2. 在第二个测试用例中,为什么会失败?

  3. 有没有办法为我上面的代码编写更好的测试?甚至更好的代码来测试。

  4. 在上面的测试用例中,我Mockery用来模拟AuthManager,但是如果我使用外观Auth::shoudReceive()->once()->andReturn(),那么它最终会起作用。Mockery这里和Auth::mock门面有什么不同吗?

谢谢。

4

1 回答 1

2

你实际上是在模拟一个新的实例,Illuminate\Auth\AuthManager而不是访问Auth你的function 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');
}

如果您签出Illuminate\Support\Facades\Facade,您会发现它会为您处理模拟。如果你真的想按照你正在做的方式来做(创建一个 Auth 的模拟实例的实例),你必须以某种方式将它注入到被测代码中。我相信假设您从 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');
}
于 2014-11-18T23:11:47.680 回答