简体   繁体   English

单元测试 Laravel 中的视图?

[英]Unit testing the views in laravel?

How to do unit testing of the controller's function which returns a view.如何对返回视图的控制器函数进行单元测试。 Here, is my controller function这是我的控制器功能

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

Here is test code这是测试代码

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

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

   $response->assertSuccessful();
}

I tried this我试过这个

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

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

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

   $response->assertSuccessful();
}

which shows error of这显示错误

Error: Call to a member function assertSuccessful() on null错误:在 null 上调用成员函数 assertSuccessful()

Any idea, How to write a test case for my index controller function?任何想法,如何为我的索引控制器功能编写测试用例?

You reassigned $response in your first assert.您在第一个断言中重新分配了 $response。 No need to do that没有必要这样做

I don't know what assertContains returns off the top of my head, but I bet it's not $this.我不知道 assertContains 会从我的脑海中返回什么,但我敢打赌它不是 $this。

Honestly, I don't know why the sample has you assigning anything to $response in the first place except the response from an HTTP query.老实说,我不知道为什么该示例让您首先将任何内容分配给 $response,除了来自 HTTP 查询的响应。

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

您可以使用此代码

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

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

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