首页 > 解决方案 > 在 laravel 中对视图进行单元测试?

问题描述

如何对返回视图的控制器功能进行单元测试。这是我的控制器功能

public function index(Request $request)
{
   $data = Data::all();
   return view('index',[
       'data' => $data
   ]);
}

这是测试代码

public function testIndex()
{
   $response = $this->withoutMiddleware();

   $response = $this->get('/user');

   $response->assertSuccessful();
}

我试过这个

public function testIndex()
{
   $response = $this->withoutMiddleware();

   $response = $this->get('/user');

   $response = $this->assertContains('data', $response->content());

   $response->assertSuccessful();
}

显示错误

错误:在 null 上调用成员函数 assertSuccessful()

任何想法,如何为我的索引控制器功能编写测试用例?

标签: phplaravelphpunit

解决方案


您在第一个断言中重新分配了 $response。没必要这样做

我不知道 assertContains 从我的脑海中返回了什么,但我敢打赌它不是 $this。

老实说,我不知道为什么示例首先要为 $response 分配任何内容,除了来自 HTTP 查询的响应。

public function testIndex()
{
   $this->withoutMiddleware();
   $response = $this->get('/user');
   $this->assertContains('data', $response->content());
   $response->assertSuccessful();
}

推荐阅读