drxrgundk062317205 2017-04-23 08:59
浏览 25
已采纳

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

this is my index function

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 is function just to check type of user and bring his profile

so how to write a test for this function?

  • 写回答

1条回答 默认 最新

  • donglinyi4313 2017-04-23 09:35
    关注

    In your case, you can simply assert that the view returned by the route has routedata.

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

    However, you could take this one step further and you could make assertions about the type of data that was sent to the view.

    First, grab the data:

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

    Now you can test the instances of these variables to ensure they were properly set as well:

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

    All together it would be something like:

    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);
    
    }
    

    I made assumptions about the types of $client and $clientProfile, so you should adjust the classes accordingly.

    Hopefully this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀