简体   繁体   English

PhpUnit和Laravel 5.4如何在测试期间模拟Session数据

[英]PhpUnit and Laravel 5.4 how to mock Session data during a test

I'm testing a class in laravel 5.4 with phpunit that uses the session to get data. 我正在使用phpunit在laravel 5.4中测试一个类,该类使用会话来获取数据。 Retrieving the session data works when accessing it directly when the app is running aka "session('consumer')" returns a value, however when i try to test a function that uses the session, I get the below error: 在应用程序运行时直接访问它时,检索会话数据是有效的“session('consumer')”返回一个值,但是当我尝试测试使用会话的函数时,我得到以下错误:

ReflectionException: Class session does not exist ReflectionException:类会话不存在

Can someone please shed some light on how to accomplish setting session data during a test. 有人可以了解如何在测试期间完成设置会话数据。

I have tried using: 我尝试过使用:

$this->session()->put([$array_value]) but get an error "class session does not exist on class_im_testing" $this->session()->put([$array_value])但是得到一个错误“class_im_testing上不存在类会话”

Thanks in advance for your help! 在此先感谢您的帮助!

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;
}

Laravel offers a lot of methods to help with testing but in order to make use of them you need to ensure you are using the correct class. Laravel提供了许多方法来帮助测试,但为了使用它们,您需要确保使用正确的类。

If you're using the default boilerplate you get a TestCase class. 如果您使用的是默认样板,则会获得TestCase类。 This is the class you need to extend in order to get method such as $this->withSession . 这是您需要扩展的类,以便获取$this->withSession

This is because the test case extends the Framework TestCase class which in turn includes many traits, among them is the the trait InteractsWithSession which is the trait which actually offers the method withSession . 这是因为测试用例扩展了Framework TestCase类,后者又包含许多特征,其中就是特征InteractsWithSession ,它是实际提供方法withSession

In addition the Laravel TestCase also extends the PhpUnit test case so you still have access to all PhpUnit assertions. 此外,Laravel TestCase还扩展了PhpUnit测试用例,因此您仍然可以访问所有PhpUnit断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM