Saturday, January 1, 2022

[FIXED] how do I mock a session_id in my integration test

Issue

I have this code in one of my controllers

$this->request->getSession()->id()

One of my integration tests fails, because this method call is not returning anything. I tried the following in my test setup, but it does not work:

$this->session([
    'id' => 'cb3d42b1-4ea0-44c6-8e29-368e948257eb',
]);

Is there a way to make $this->request->getSession()->id() return a value in the integration test setup?


Solution

The \Cake\TestSuite\IntegrationTestTrait::session() method accepts values that are being written into the session for the test request, ie session data, it will not configure any other session aspects like the ID.

Normally CakePHP's session class would set a value of cli for the session id when running on the CLI, simply by doing $this->id('cli'), but as of PHP 7.2 that will not work anymore when there's already been output generated, also as of CakePHP 3.5, CakePHP actively prevents setting the ID in case headers have already been sent, ie you probably won't be able to change the ID in your test cases.

So what can you do? Well, you can settle for a fixed value and set it in your test bootstrap (tests/bootstrap.php), which is what the default test bootstrap in the CakePHP 4.x application template now does too, ie simply do:

session_id('my-custom-id');


Answered By - ndm

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.