Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajtrichards's avatar

PHPUnit - Test and Middleware has 2 different session tokens

In my App i've written some middleware that checks if a Session variable called contract_id is present - if not, it redirects to a page where the user can set a contract ID. This works fine when running in the browser.

However, when it comes to writing a unit test I keep getting a failure. My unit test is:

<?php

use App\User; use Illuminate\Http\Request;

class SecurityTest extends TestCase {

public function testOkIfLoggedIn()
{

    $user = new User(array('user_forename' => 'Alex', 'user_surname' => 'Richards', 'id' => 1));
    $this->be($user);

    $this->session(['contract_id' => 1]);

    $response = $this->call('GET', '/');

    $this->assertEquals(200, $response->getStatusCode());

}

}

Within my application controller for that specific route I have 2 middleware's included - Auth and my custom middleware UsersContract.

My UsersContract.php middleware is:

`<?php namespace App\Http\Middleware;

use Closure; use Illuminate\Contracts\Routing\Middleware;

class UsersContract implements Middleware {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{

    $current_contract_id = \Session::get('contract_id');

    if(!is_numeric($current_contract_id)){

        /*
        **  The current user is logged in but they haven't selected a Contract
        **  Redirect them to the Contract list and let them select.
        */
        return redirect('/contract/select');

    }

    return $next($request);

}

}

When I run my unit test, if I print out the session variables in the unit test script I can see Contract ID but if I print the session variables out in the middleware I don't see Contract ID and I get a new session Token.

0 likes
0 replies

Please or to participate in this conversation.