Laravel 拉威尔试验未通过

Laravel 拉威尔试验未通过,laravel,phpunit,laravel-7,laravel-testing,Laravel,Phpunit,Laravel 7,Laravel Testing,因此,我正在学习为我的应用程序进行测试,以及其中一个它不想通过的测试,这是逻辑:基本上,当用户请求主页时,我希望数据库列表计数为0,这是通过的,然后我还希望会话有一个错误键NoBook,在这里它失败。这是我尝试过的代码: class BookDisplayManagmentTest extends TestCase { use RefreshDatabase; /** @test */ public function Show_error_message_when_th

因此,我正在学习为我的应用程序进行测试,以及其中一个它不想通过的测试,这是逻辑:基本上,当用户请求主页时,我希望数据库列表计数为0,这是通过的,然后我还希望会话有一个错误键
NoBook
,在这里它失败。这是我尝试过的代码:

class BookDisplayManagmentTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function Show_error_message_when_there_is_no_book_to_display_in_index_page()
    {
        //Request the home page
        $response = $this->get(route('home'));

        // I expect the count on the database book equal 0
        $this->assertCount(0, book::all());

        //Then I also expect that the session will flash an error with key NoBook
        $response->assertSessionHasErrors('NoBook');
    }

}
但问题是我得到了这个错误:

Session is missing expected key [errors]. Failed asserting that false is true.
以及添加会话错误的代码:

<?php

namespace App\Http\Controllers;

use App\Books;
use Illuminate\Http\Request;

class IndexController extends Controller
{
      /** @show index function */
        public function index()
        {
            $book = Books::paginate(7);
            if(!$book->count())
            {
                session()->now('NoBook','There is no books at the moment');
            }
            return view('index', compact('book'));
        }
}

您使用的是
session()
,它向会话添加了一个不是错误键的键

因此,由于您没有从控制器传递错误,因此您的测试“成功”失败

如果要将错误传递给会话,必须使用MessageBag,例如使用以下代码:

      /** @show index function */
        public function index()
        {
            $book = Books::paginate(7);
            $errors = [];

            if(!$book->count())
            {
                $errors['NoBook'] = 'There is no books at the moment';
            }
            return view('index', compact('book'))->withErrors($errors);
        }


您可以共享将错误添加到会话中的代码吗?如果(!$Book->count()){session()->NoBook',“目前没有书”);}请将代码添加到初始问题中,尝试添加
$this->assertSessionHasErrors()
$response->assertSessionHasErrors('NoBook')之前@ChristopherHubert我添加了代码我正在传递会话错误session()->现在('NoBook','There'snow'snow's not books');我试过你的代码不起作用也请检查更新的解释和修复的代码非常感谢我现在理解了发生的事情,再次感谢:)非常欢迎!编写测试是保持良好编码标准、保持编码的好方法,不要忘记通过StackOverflow分享您的知识