【问题标题】:PhpUnit and Laravel 5.4 how to mock Session data during a testPhpUnit 和 Laravel 5.4 如何在测试期间模拟 Session 数据
【发布时间】:2019-01-28 10:59:03
【问题描述】:

我正在使用 phpunit 测试 laravel 5.4 中的一个类,该类使用会话获取数据。在应用程序运行时直接访问会话数据时检索会话数据有效,即“会话('consumer')”返回一个值,但是当我尝试测试使用会话的函数时,出现以下错误:

ReflectionException:类会话不存在

有人可以说明如何在测试期间完成设置会话数据。

我尝试过使用:

$this->session()->put([$array_value]) 但收到错误“class_im_testing 上不存在课程会话”

提前感谢您的帮助!

public function test_get_user()
{
    $mockUser =  [
        'id' => 'cf442564-d076-4198-beb5-edef5aa51a69',
        'name' => 'John Doe',
        'fname' => 'John',
        'lname' => 'Doe',  
    ];

    session->put('consumer', [
        'id' => 'cf442564-d076-4198-beb5-edef5aa51a69',
        'name' => 'John Doe',
        'fname' => 'John',
        'lname' => 'Doe',  
    ]);

    $user = $this->repo->getUser();

    $this->assertEqual($user, $mockUser);
}

public function getUser()
{
   $user = new User(session('consumer'));
   return $user;
}

【问题讨论】:

  • 根据the docs应该是$this->withSession([ ... ])
  • @apokryfos 使用“$this->withSession([...])”时返回的错误调用未定义函数 class_im_testing::withSession
  • @Leevashan 该方法应该在测试用例类中,而不是在您正在测试的类中。
  • 确保你的测试用例扩展了 laravel 自带的 TestCase 类,而不是默认的 PhpUnit 测试用例类
  • Laravel 的测试用例扩展了this TestCase,它有很多额外的方法,也包括很多特征。您的withSession 方法实际上来自InteractsWithSession,这是包含的特征之一。

标签: php laravel phpunit laravel-session


【解决方案1】:

Laravel 提供了很多方法来帮助测试,但为了使用它们,您需要确保使用正确的类。

如果您使用的是默认样板,您将获得 TestCase 类。这是您需要扩展的类以获取诸如$this->withSession 之类的方法。

这是因为测试用例扩展了框架TestCase 类,该类又包含许多特征,其中是特征InteractsWithSession,它实际上是提供方法withSession 的特征。

此外,Laravel TestCase 还扩展了 PhpUnit 测试用例,因此您仍然可以访问所有 PhpUnit 断言。

【讨论】:

  • 感谢您的指导,因为 Leevashan 指出导入正确的 TestCase 类解决了我们的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2017-07-28
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 2019-02-17
  • 2017-11-10
相关资源
最近更新 更多