Skip to content
Latchkey

PHPUnit: Allowed Memory Size Exhausted During the Test Run in CI

A long PHPUnit run accumulates memory - fixtures, container instances, static caches, and coverage data add up. When it exceeds PHP's memory_limit, the run dies mid-suite with "Allowed memory size exhausted", often near the end of a large suite.

What this error means

PHPUnit dies partway with "Fatal error: Allowed memory size of N bytes exhausted", frequently during coverage or in a large suite. Running a subset passes; the full suite fails.

phpunit
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to
allocate 65536 bytes) in /app/vendor/phpunit/.../CodeCoverage.php on line 320

Common causes

memory_limit too low for the suite

Coverage data and per-test fixtures accumulate; a finite CLI memory_limit is exceeded before the suite finishes.

Tests leak state between cases

Static caches, undestroyed containers, or growing fixtures that are not reset in tearDown make memory climb across tests.

How to fix it

Raise the limit for the run

php
php -d memory_limit=512M vendor/bin/phpunit
# unlimited for a one-off large run
php -d memory_limit=-1 vendor/bin/phpunit

Reset state between tests

  1. Clear static caches and tear down heavy objects in tearDown().
  2. Avoid holding large fixtures in static properties.
  3. Run coverage in a separate job so its memory cost is isolated.
php
protected function tearDown(): void
{
    Registry::reset();
    parent::tearDown();
}

Split or shard a very large suite

Run test groups separately so no single process accumulates the whole suite's memory.

php
vendor/bin/phpunit --testsuite unit
vendor/bin/phpunit --testsuite integration

How to prevent it

  • Set a sensible CLI memory_limit for test jobs.
  • Reset static/shared state in tearDown so memory stays flat across tests.
  • Isolate coverage and shard large suites to bound per-process memory.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →