控制器中的laravel单元测试索引功能

时间:2017-04-23 08:59:44

标签: php laravel unit-testing laravel-5 laravel-5.1

这是我的索引功能

public function index($alias, $profileId)
{
    $this->setClientAndClientProfile($alias, $profileId);

    $routeData = Routedata
                        ::where('client_id', $this->client->id)
                        ->paginate(10);

    return view('client.route_data.index', compact('routedata'))->with('client', $this->client)->with('clientProfile', $this->clientProfile);
}

setClientAndClientProfile仅用于检查用户类型并带来他的个人资料

那么如何为这个函数编写测试?

1 个答案:

答案 0 :(得分:1)

在您的情况下,您可以简单地断言路由返回的视图具有routedata。

public function testIndex()
{
    $this->call('GET', '/path/to/my/controlller/method');

    $this->assertViewHas('routedata');
    $this->assertViewHas('client');
    $this->assertViewHas('clientProfile');
}

但是,您可以更进一步,并且可以对发送到视图的数据类型进行断言。

首先,抓住数据:

$routedata = $response->original->getData()['routedata'];
$client = $response->original->getData()['client'];
$clientProfile = $response->original->getData()['clientProfile '];

现在,您可以测试这些变量的instances以确保它们也已正确设置:

$this->assertInstanceOf('\Illuminate\Database\Eloquent\Collection', $routedata);
$this->assertInstanceOf('\App\Client', $client);
$this->assertInstanceOf('\App\ClientProfile', $clientProfile);

总之它会像:

public function testIndex()
{
    $this->call('GET', '/path/to/my/controlller/method');

    $this->assertViewHas('routedata');
    $this->assertViewHas('client');
    $this->assertViewHas('clientProfile');

    $routedata = $response->original->getData()['routedata'];
    $client = $response->original->getData()['client'];
    $clientProfile = $response->original->getData()['clientProfile '];

    $this->assertInstanceOf('\Illuminate\Database\Eloquent\Collection', $routedata);
    $this->assertInstanceOf('\App\Client', $client);
    $this->assertInstanceOf('\App\ClientProfile', $clientProfile);

}

我对$client$clientProfile的类型做了假设,因此您应该相应地调整类。

希望这有帮助。