Maxime Bury

KnpRadBundle + PHPUnit

I was trying out the new KnpRadBundle¬†and when came the time to write to write unit tests, it didn’t work : my classes weren’t autoloaded properly.

It took me the best part of an afternoon to figure out, so I thought I should post it in case anyone stumbles upon this problem (perhaps I missed something …). Without further ado, here is the code :

phpunit.xml.dist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="UTF-8"?>

<!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit
    backupGlobals               = "false"
    backupStaticAttributes      = "false"
    colors                      = "true"
    convertErrorsToExceptions   = "true"
    convertNoticesToExceptions  = "true"
    convertWarningsToExceptions = "true"
    processIsolation            = "false"
    stopOnFailure               = "false"
    syntaxCheck                 = "false"
    bootstrap                   = "src/YourProjectName/Tests/bootstrap.php" >

    <testsuites>
        <testsuite name="YourProjectName Test Suite">
            <!-- Note the Test.php suffix -->
            <directory suffix="Test.php">src/YourProjectName/Tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <blacklist>
      <directory>src/YourProjectName/Tests</directory>
            <directory>src/YourProjectName/Resources</directory>
            <directory>vendor</directory>
        </blacklist>
    </filter>
</phpunit>
bootstrap.php
1
2
3
4
5
6
7
8
9
10
<?php
# src/YourProjectName/Tests/

if (file_exists($file = __DIR__.'/../../../vendor/.composer/autoload.php')) {
    $loader = require_once $file;

    $loader->add('YourProjectName', __DIR__.'/../..');
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

That’s it, it should work!