Skip to content
Latchkey

PHPUnit "Allowed memory size exhausted" - Fix OOM in Tests

The PHP process running PHPUnit hit PHP’s memory_limit and was killed mid-suite. Either the limit is too low for the suite, or a test (or code under test) accumulates memory across cases.

What this error means

A PHPUnit run dies partway with "Allowed memory size of N bytes exhausted", often during a large data-provider test or with coverage enabled. The same suite may pass locally where memory_limit is higher.

PHPUnit output
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to
allocate 20480 bytes) in /app/vendor/phpunit/phpunit/src/Framework/TestResult.php
on line 700

Common causes

memory_limit too low for the suite

Code coverage, large fixtures, or big data providers can push memory past a 128M default, especially in CI.

A memory leak across tests

Static caches, unclosed resources, or growing global state accumulate across the run, so memory climbs until it exhausts the limit.

How to fix it

Raise the memory limit for the run

Terminal
php -d memory_limit=-1 vendor/bin/phpunit
# or a finite ceiling
php -d memory_limit=1G vendor/bin/phpunit

Reduce per-run overhead

  1. Run coverage in a separate job; coverage (Xdebug/PCOV) is memory-heavy.
  2. Split a huge suite into shards/testsuites run in parallel.
  3. Free large fixtures in tearDown() and avoid unbounded static caches.

Hunt the leak if memory grows over time

If memory climbs steadily rather than spiking once, a leak is more likely than a low limit.

How to prevent it

  • Set a sufficient memory_limit for the test job (or -1 in CI).
  • Run coverage separately from the plain test pass.
  • Clean up fixtures and static state in tearDown().

Related guides

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