Autoloading Hamcrest functions for PHPUnit in Symfony2

Hamcrest offers plain PHP functions that wrap calls to its static methods. Examples are assertThat(), equalTo(), and so on.

To use these functions, you must first include Hamcrest.php in your tests. Rather than including that file at the top of each test, it can be autoloaded in your PHPUnit bootstrap script.

By default, Symfony2 uses app/bootstrap.php.cache as the bootstrap script, which is problematic since any changes to that file will likely be overwritten.

The workaround is simple:

1. Make your own bootstrap script and include app/bootstrap.php.cache at the top.
2. Change app/phpunit.xml to point to your custom bootstrap script. If you don’t have that file, then copy app/phpunit.xml.dist.

Here is an example of my custom bootstrap that loads Hamcrest.php:

<?php

# src/Test/bootstrap.php

namespace Test;

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require_once __DIR__.'/../../app/bootstrap.php.cache';

// Load Hamcrest functions
$utilPath = $loader->findFile('\Hamcrest\Util');
require dirname($utilPath).'/../Hamcrest.php';

Composer.json is out of sync with your lock file

So I got that message when running composer.phar install.

I found that it’s most likely caused by a mismatch between the hash value stored in composer.lock and what it ought to be based on composer.json.

Composer tells you to run composer.phar update to fix it. I warn you though.. don’t run that command (without additional arguments) unless you know of the consequences. Depending on how you configured composer.json, Composer may update one of your dependencies to an unstable/dev version and potentially break your app.

Luckily, fixing the "Composer.json is out of sync with your lock file" error is easy. Run composer.phar update nothing. This tells Composer to update only the nothing package. Because that is not a real package, Composer skips it and finishes by re-calculating the hash values in composer.lock. Hopefully… problem solved.