这是我的索引函数
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 的功能只是检查用户类型并提供他的个人资料
那么如何为这个函数编写测试呢?
最佳答案
在您的情况下,您可以简单地断言路由返回的 View 具有路由数据。
public function testIndex()
{
$this->call('GET', '/path/to/my/controlller/method');
$this->assertViewHas('routedata');
$this->assertViewHas('client');
$this->assertViewHas('clientProfile');
}
但是,您可以更进一步,可以对发送到 View 的数据类型做出断言。
首先,获取数据:
$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);
总的来说,它会是这样的:
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
的类型进行了假设,因此您应该相应地调整类。
希望这有帮助。
关于php - Laravel Controller 中的单元测试索引函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569191/