Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
public function testItems(): void
{
$items = $this->loadItems();
$this->assertNotEmpty($items);
}
/** @return list<string> */
private function loadItems(): array
{
return ['foo'];
}
}
Why is it reported? #
This rule is part of phpstan-phpunit. It is enabled when phpstan-strict-rules is installed and bleeding edge is turned on.
assertEmpty() and assertNotEmpty() mirror PHP’s empty() construct, which treats many different values as empty: null, false, 0, 0.0, '', '0', and []. An assertion like assertNotEmpty($value) therefore passes for values the test probably did not intend to accept, and assertEmpty($value) passes for values of the wrong type entirely, such as '0' or false when an empty array was expected. This makes the test less precise and can hide bugs.
The same reasoning is behind the empty.notAllowed rule from phpstan-strict-rules.
How to fix it #
Replace the assertion with one that checks the exact expected value or type.
For arrays and countable values, use assertCount() or compare against an empty array:
<?php declare(strict_types = 1);
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
public function testItems(): void
{
$items = $this->loadItems();
- $this->assertNotEmpty($items);
+ $this->assertCount(1, $items);
}
}
-$this->assertEmpty($items);
+$this->assertSame([], $items);
For strings, compare against the empty string:
-$this->assertEmpty($name);
+$this->assertSame('', $name);
-$this->assertNotEmpty($name);
+$this->assertNotSame('', $name);
For nullable values, use assertNull() or assertNotNull():
-$this->assertNotEmpty($user);
+$this->assertNotNull($user);
How to ignore this error #
You can use the identifier phpunit.assertEmpty to ignore this error using a comment:
// @phpstan-ignore phpunit.assertEmpty
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: phpunit.assertEmpty
Rules that report this error #
- PHPStan\Rules\PHPUnit\AssertEmptyIsDiscouragedRule [1] phpstan/phpstan-phpunit