【问题标题】:Laravel test not passingLaravel 测试未通过
【发布时间】:2020-08-08 18:56:37
【问题描述】:

所以我正在学习为我的应用程序进行测试以及它不想通过的测试之一,这是逻辑:基本上,当用户请求主页时,我希望数据库列表计数将是 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'));
        }
}

【问题讨论】:

  • 您能分享将错误添加到会话中的代码吗?
  • if(!$Book->count()) { session()->now('NoBook','暂时没有书'); }
  • 请将代码添加到您最初的问题中????
  • 尝试在$response-&gt;assertSessionHasErrors('NoBook');之前添加$this-&gt;assertSessionHasErrors();
  • @ChristopheHubert 我确实添加了代码

标签: laravel phpunit laravel-7 laravel-testing


【解决方案1】:

您正在使用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);
        }

【讨论】:

  • 我正在传递会话错误 session()->now('NoBook','目前没有书籍');我试过你的代码也没有用
  • 请查看更新说明和修复代码
  • 非常感谢,我现在明白发生了什么,再次感谢您:)
  • 不客气!编写测试是保持良好编码标准的好方法,保持编码,不要忘记通过 StackOverflow 分享你的知识?
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 2018-07-20
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多