Laravel单元测试通过身份验证调用来自测试的路由

时间:2015-01-07 10:08:27

标签: php api unit-testing laravel

我正在测试我的api。在调用路由之前,我将用户登录到应用程序。 问题是,在身份验证之后,用户的ID未在路由呼叫中分配给Auth::id()

以下是该方案:

测试方法:

public function testApiGetOrder()
{
    var_dump($this->user);  // first dump
    Auth::login($this->user); // Can't use $this->be($this->user) here, it would not help anyway...
    var_dump(Auth::id());  // second dump

    $response = $this->call('GET', '/order/' . $this->order->getKey());

    $this->assertResponseOk();
    $this->assertJson($response->getContent());
    $this->assertJsonStringEqualsJsonString($this->order->toJson(), $response->getContent());
}

OrderController的方法:

public function show($id)
{
    var_dump(Auth::id());  // third dump
    var_dump(Auth::user()->getKey());   // fourth dump

    // Calling model's logic here
}

testApiGetOrder的输出:

首次转储:object(User)
第二次转储:int(1)
第三次转储:NULL
第四次转储:int(1)

为什么用户ID的值未分配给Auth::id()

1 个答案:

答案 0 :(得分:2)

你不是在谈论同一个Auth的例子。

在您的测试中,您获得了一个Auth库实例,您登录后会获得数据。 当你进行呼叫时,控制器拥有它自己的auth实例(在Laravel框架内运行)

创建测试的更清晰的方法是使用模拟Auth库。它由Laravel测试,在单元测试期间,您要测试最小的代码。

public function testApiGetOrder()
{
    Auth::shouldReceive('id')->with($this->user->getKey())
                             ->once()->andReturn($this->user);

    Auth::shouldReceive('user')->once()->andReturn($this->user);

    $response = $this->call('GET', '/order/' . $this->order->getKey());

    $this->assertResponseOk();
    $this->assertJson($response->getContent());
    $this->assertJsonStringEqualsJsonString($this->order->toJson(), $response->getContent());
}
相关问题