Composer/PHPUnit on Windows Shell

Are you tired of typing php [PATH]/composer.phar on the console all the time? Wouldn’t it be easier to just type composer and you’re done? Fortunately this isn’t very hard to configure.

Save the composer.phar file to some folder, e.g. somewhere in your “Program Files” folder. I assume it’s C:\Program Files\Composer in this little tutorial.

Add a BAT file named composer.bat to that folder, which contains:

@ECHO OFF
SET "COMPOSER_INSTALL_DIR=C:\Program Files\Composer"
@ECHO ON
php "%COMPOSER_INSTALL_DIR%\composer.phar" %*

Add C:\Program Files\Composer to the PATH setting of you operating system. If you don’t know how it works, just Google it.

Note: If PHP isn’t runable on your console via a simple php, you should also add your PHP folder to the PATH setting. Otherwise you have to write the full path to php.exe in the BAT file.

Now you can run the Composer commands from any folder:

composer self-update  # (may only work if the console runs with admin privileges)
composer install
composer update
...

The same works for PHPUnit’s phar distribution.

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.