PHPUnit: Remove non-deterministic dependencies

Unit testing is great! But sometimes there are situations where it can become really tough to write proper tests for your code. One of these situations is when your code doesn’t work totally predictable, when it has some kind of randomness in it, that is intended. Then you usually have one of those functions in your code:

  • tempnam(), uniqid()
  • rand(), mt_rand(), shuffle() or any other randomized function
  • time(), date(), new \DateTime() or anything that has to do with the current time

The list isn’t complete, just wanted to mention the most common ones. Those functions are bad for testing, because tests have to be repeatable and those ones will most likely produce a different result on every call.

So how to get rid of the randomness and create predictable and therefore repeatable unit test?
Read more

PHPUnit: contains vs. stringContains

Note to myself: If I ever see that error again when running PHPUnit tests

Invalid argument supplied for foreach()

phar://C:/Program Files (x86)/PHPUnit/phpunit.phar/PHPUnit/Framework/Constraint/TraversableContains.php:110
phar://C:/Program Files (x86)/PHPUnit/phpunit.phar/PHPUnit/Framework/Constraint.php:82
phar://C:/Program Files (x86)/PHPUnit/phpunit.phar/PHPUnit/Framework/Constraint/And.php:113

please remember that $this->contains() is not the same as $this->stringContains(). The first one is a constraint for arrays, the second one is for strings.