【问题标题】:Call to undefined method Session::has() in Laravel 5 + Codeception functional testing在 Laravel 5 + Codeception 功能测试中调用未定义的方法 Session::has()
【发布时间】:2016-08-04 14:30:37
【问题描述】:

我在 Laravel 5 中使用 Codeception 运行了一些功能测试。

下面是一个示例测试

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class HomePageTestCest
{
    use WithoutMiddleware;

    public function _before(FunctionalTester $I)
    {
        //some setup to run
    }

    public function _after(FunctionalTester $I)
    {
    }

    // tests
    public function tryToTest(FunctionalTester $I)
    {
        $I->wantToTest('If i can go to home page without errors');
        $I->amOnPage('/');
        $I->canSee('WELCOME TO HOMEPAGE');
    }
}

但我在运行测试时遇到以下错误:

Fatal error: Call to undefined method Session::has() in /var/www/laravel5/storage/framework/views/e7953b3ce9b90e51d4cfdb279790953bbe25dc9a.php on line 225

在第 225 行我有:

<?php if(Session::has('someKey')): ?>
  //some html code
<?php endif; ?>

我认为问题出在会话驱动程序上。我也尝试实现this,但没有任何改变。

希望能得到一些帮助。提前致谢。

【问题讨论】:

  • 将完整的命名空间写为:Illuminate\Support\Facades\Session::has('something')
  • 功能测试是否需要专门写完整的命名空间??
  • @hamedmehryar 您的解决方案有效,但您能解释一下为什么我必须定义整个命名空间吗??
  • 可能Session 未列在app.php 配置文件的aliases 数组中。
  • 不,我检查并列出了它。 Config::get() 也一样。

标签: php session laravel-5.2 codeception php-5.6


【解决方案1】:

LARAVEL 5.2 中,他们还创建了类似 helper 的会话类

你在哪里可以像这样使用它

session()->has('key')

DOCUMENTATION SESSION

namespace App\Http\Controllers;

// import session class using alias
use Session;

class SampleController exntends Controller {

    public function __construct() {

    }

    public function index() {
        // print session values
        var_dump(Session::all());
    }

}

【讨论】:

  • 嘿,对不起,我以某种方式完全忽略了您的解决方案。您的解决方案也有效。但是您知道原因吗,为什么 Session:: 不起作用?提前谢谢。
  • 我相信别名类是自动需要的,这与 laravel 4 不同。这是一个讨论您的问题的链接。如果您想使用外观别名,请使用 use Session 导入类;那么你已经可以使用 Session::has('key') 了。我更新了我的答案,这样你就可以理解我的意思了
  • 嘿,谢谢回复。是的,我已经尝试过了,但没有奏效。唯一对测试有用的是当我使用像 Illuminate\Support\Facades\Session 这样的完整路径时,它确实是有线的,就像我在下面的回答中描述的那样。我正在寻找一个原因,或者最准确的答案。
【解决方案2】:

感谢 hamedmehryar 的解决方案。我不知道为什么,但由于某种原因,我必须为外观定义整个命名空间,即使它们已经在 config/app.php 内的“别名”中定义。例如:

Session::has()

应该是这样的

Illuminate\Support\Facades\Session::has()

我在这里解释过,所以如果有人遇到这个问题,可以从这里解决。

【讨论】:

    【解决方案3】:

    别忘了

    use Illuminate\Http\Request;

    并像这样使用会话

    $request-&gt;session()-&gt;has('key');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 2016-06-05
      • 1970-01-01
      • 2018-03-05
      • 2014-02-21
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多