Search code examples
unit-testingzend-frameworktestingphpunitphing

phing and phpunit + bootstrap


How to run PHPUnit test suite with bootstrap file with phing?

My app structure:

application/
library/
tests/
  application/
  library/
  bootstrap.php
  phpunit.xml
build.xml

phpunit.xml:

<phpunit bootstrap="./bootstrap.php" colors="true">
    <testsuite name="Application Test Suite">
        <directory>./</directory>
    </testsuite>
    <filter>
        <whitelist>
            <directory
              suffix=".php">../library/</directory>
            <directory
              suffix=".php">../application/</directory>
            <exclude>
                <directory
                  suffix=".phtml">../application/</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

then:

cd /path/to/app/tests/
phpunit
#all test passed

But how do I run the tests from /path/to/app/ dir? The problem is, that the bootstrap.php depends on relative paths to library and application.

If I run phpunit --configuration tests/phpunit.xml /tests I got a bunch of file not found errors.

How do I write build.xml file for phing to run the tests the same way phpunit.xml does?


Solution

  • I Think the best way is to create an small PHP Script to initalize your Unit tests, iam doing the following:

    In my phpunit.xml / bootstrap="./initalize.php"

    initalize.php

    define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
    define('APPLICATION_PATH', BASE_PATH . '/application');
    
    // Include path
    set_include_path(
        '.'
        . PATH_SEPARATOR . BASE_PATH . '/library'
        . PATH_SEPARATOR . get_include_path()
    );
    
    // Define application environment
    define('APPLICATION_ENV', 'testing');
    require_once 'BaseTest.php';
    

    BaseTest.php

    abstract class BaseTest extends Zend_Test_PHPUnit_ControllerTestCase
    {
    
    /**
     * Application
     *
     * @var Zend_Application
     */
    public $application;
    
    /**
     * SetUp for Unit tests
     *
     * @return void
     */
    public function setUp()
    {
        $session = new Zend_Session_Namespace();
        $this->application = new Zend_Application(
                        APPLICATION_ENV,
                        APPLICATION_PATH . '/configs/application.ini'
        );
    
        $this->bootstrap = array($this, 'appBootstrap');
    
        Zend_Session::$_unitTestEnabled;
    
        parent::setUp();
    }
    
    /**
     * Bootstrap
     *
     * @return void
     */
    public function appBootstrap()
    {
        $this->application->bootstrap();
    }
    }
    

    All my Unit tests are extending BaseTest Class, it works like a charm.