在laravel中对视图进行单元测试?

时间:2019-04-04 06:34:37

标签: php laravel phpunit

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

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()

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

3 个答案:

答案 0 :(得分:0)

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

我不知道assertContains的返回值是多少,但是我敢打赌这不是$ this。

老实说,我不知道为什么样本中除了HTTP查询的响应之外,首先将任何内容分配给$ response。

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

答案 1 :(得分:0)

您也可以使用

googleSignInAccount.displayName.split(" ");

https://laravel.com/docs/7.x/http-tests#assert-see-text

答案 2 :(得分:0)

您可以使用此代码

$this->get('/user')->assertViewHas('data');
相关问题