laravel控制器中的单元测试索引函数

laravel unit test index function in controller

这是我的索引函数

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 的功能只是检查用户类型并带来他的个人资料

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

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

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的类型做了假设,所以你应该相应地调整类。

希望这对您有所帮助。