繁体   English   中英

单元测试 Laravel 中的视图?

[英]Unit testing the views in 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()

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

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

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

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

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

你也可以使用

$response->assertSeeText('data');

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

您可以使用此代码

$this->get('/user')->assertViewHas('data');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM