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

victorpfm's avatar

TokenMismatchException in Unit Tests

I am getting a TokenMismatchException when I try to test a post request.

Laravel should disable csrf when running tests. I've inspected the VerifyCsrfToken's handle method:

public function handle($request, Closure $next)
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->inExceptArray($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

Then I checked the runningUnitTests method:

protected function runningUnitTests()
    {
        return $this->app->runningInConsole() && $this->app->runningUnitTests();
    }

and the App::runningUnitTests method:

public function runningUnitTests()
    {
        return $this['env'] === 'testing';
    }

In my tests, when I dump env('APP_ENV') and app()->env I get different values:

APP_ENV is testing but app()->env is local

I believe this is the reason I'm getting this TokenMismatchException but I don't know how to fix it.

0 likes
7 replies
Cronix's avatar

what does your phpunit.xml look like? Is the APP_ENV set to testing?

victorpfm's avatar

It is the default phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>
victorpfm's avatar

I'm using winnmp (nginx) as my webserver. Maybe phpunit is interacting with nginx?

Cronix's avatar

phpunit runs through the php-cli though, not the web server.

victorpfm's avatar

Solved it by clearing config cache. The local server stops working but tests work.

Is there a way to make them both work?

1 like

Please or to participate in this conversation.