chris342423
chris342423

Reputation: 451

PHPUnit: Is there something like "assertExistsNotNull"?

I recently detected the following problem:

self::assertNull($someArray[$someIndex]);

If $someIndex is not an existing index of $someArray, $someArray[$someIndex] will evaluate to null and assertNull(null) will say everything is okay. So basically PHPUnit is hiding a problem.

Is there something like

self::assertExistsNotNull($someArray[$someIndex]);

which only is true if $someArray[$someIndex] exists and is not null?

Upvotes: 1

Views: 109

Answers (3)

gealex
gealex

Reputation: 115

You could write your own assertion : https://phpunit.de/manual/6.5/en/extending-phpunit.html#extending-phpunit.custom-assertions

Or write something like that :

self::assertThat($someArray, self::logicalAnd(self::arrayHasKey($someIndex), self::logicalNot(self::isNull())));

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35357

It seems like your problem is not that PHPUnit is "hiding" problems but that you are hiding problems with your PHP error reporting settings.

PHP will throw a notice for an undefined index. I'd highly recommend you both develop and test with error_reporting set to E_ALL and display_errors enabled. Therefore, during testing, you will see a problem if it is undefined and therefore, you don't need to add a new assertion.

Upvotes: 0

gogaz
gogaz

Reputation: 2400

You can use assertArrayHasKey() in addition to assertNull() as explained in the documentation

Upvotes: 2

Related Questions