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.

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

报告相同问题?

悬赏问题

  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果