Laravel 测试未通过

Laravel test not passing

所以我正在学习为我的应用程序做测试以及它不想通过的测试之一,这是逻辑:基本上,当用户请求主页时,我希望数据库列表计数将为 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(),它正在向会话添加一个密钥,该密钥不是错误密钥

因此,由于您没有从控制器传递错误 - 那么您的测试 "successfully" 失败。

如果要将错误传递给会话,则必须使用 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);
        }