Articles Snippets Projects

Resolving Database Deadlocks When Running Laravel Tests with ParaTest in PhpStorm

April 4th ʼ25 2 weeks ago

3 min 411 words

While PhpStorm added official support for ParaTest in version 2022.3, many developers encounter database deadlock issues when trying to use this feature with Laravel applications.

The Problem

When running tests with ParaTest in PhpStorm, you might encounter MySQL/Database deadlock errors that look like this:

Illuminate\Database\QueryException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

This happens because multiple test processes are trying to access the database simultaneously, causing lock contention.

The most frustrating part is that running the same tests with the command line using php artisan test --parallel works perfectly fine! So why does it fail in PhpStorm?

Understanding the Cause

The reason is that when you run parallel tests through the command line with php artisan test --parallel, Laravel automatically sets environment variables that tell the framework to create separate database connections for each test process. However, PhpStorm's ParaTest integration doesn't set these environment variables by default.

The Solution

The fix is surprisingly simple - you just need to manually add the required environment variables to your PhpStorm test run configuration:

  1. Right-click on your tests directory in PhpStorm

  2. Select "More Run/Debug" → "Modify Run Configuration..."

  3. In the dialog that appears, find the "Environment variables" field

  4. Add the following and click "OK" to save

LARAVEL_PARALLEL_TESTING=1;LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES=1

What These Variables Do

When LARAVEL_PARALLEL_TESTING is set to 1, Laravel will create a separate database connection for each test process. The connection name is suffixed with the test token (e.g., testing_1, testing_2).

When LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES is set to 1, Laravel will recreate the database for each process, preventing conflicts between concurrent test executions.

Testing Without Deadlocks

After adding these environment variables, your tests should run in parallel without any deadlock issues:

Happy testing!