php - Laravel Controller 中的单元测试索引函数

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

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

最佳答案

在您的情况下,您可以简单地断言路由返回的 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/

相关文章:

java - 如何在不初始化类的情况下模拟内部成员

php - 对数组进行排序并显示其对应者

php - 我通过迁移重命名破坏了我的 Laravel 框架

javascript - Jest 中的 'describe' 和 'test' 有什么区别?

c# - 在 Specflow 中,我可以将一个测试作为另一个步骤运行吗?

javascript - 将 axios 中的 Prop 传递给 Vue.js?

php - 获取 Woocommerce 产品类别图像 url

php - 如何检查 JFactory::getSession() 中的 session 是否已设置?

php - 配置文件中的MySQL连接错误

javascript - Laravel 中通过 Ajax 上传文件