Company dedicated to web development, graphic design, photography and web hosting.

How to configure code coverage with Selenium in Phpunit
Published Monday, 24th of February 2014
Overview Running Selenium with Phpunit we don't have code coverage by default. We need to configure some files to have code coverage in php like with have with unit tests. After that, we can generate code coverage report in Phpunit. The configuration was done in Selenium 2.39 and Phpunit 3.7.31 with php 5.3Alias table
${PEAR_PATH}/usr/share/php/PEARThe directory where pear is installed
${PREPEND_PATH}/var/wwwThe directory where the prepend file is created
Steps to follow Create a prepend file
  1. First we need to create a file that will be executed after every php file executed, and there, we will execute the needed code from phpunit seleinum coverage.
    Create the file ${PREPEND_PATH}/prepend.php with the next content:
    $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = get_cfg_var('phpunit_coverage_data_directory');
    include get_cfg_var('pear_path').'/pear/PHPUnit/Extensions/SeleniumCommon/prepend.php';
    It will execute the selenium prepend file every php file execution.

  2. Create also a temporary folder where the temporary files generated by phpunit will be stored. Be sure that the user executing apache and php has permission to write there.
    mkdir ${PREPEND_PATH}/tmp
Configure php.ini
  1. Add four lines to your php.ini configuration file:
    auto_prepend_file = "${PREPEND_PATH}/prepend.php"
    auto_append_file = "${PEAR_PATH}/pear/PHPUnit/Extensions/SeleniumCommon/append.php"
    phpunit_coverage_data_directory = "${PREPEND_PATH}/tmp"
    pear_path = "${PEAR_PATH}"
    Be sure that such lines are defined after auto_prepend_file and auto_append_file, or just comment both lines.
Modify Phpunit
  1. Locate the file ${PREPEND_PATH}/pear/PHPUnit/Extensions/SeleniumCommon/phpunit_coverage.php and replace the line 51:
    with the next three lines:
Modify Apache
  1. Modify the httpd.conf file and add access to pear directory via web:
    <Directory "${PEAR_PATH}/pear/PHPUnit/Extensions/SeleniumCommon">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
  2. Add also an alias to the folder in httpd.conf so you can access easily later:
    Alias /phpunit ${PEAR_PATH}/pear/PHPUnit/Extensions/SeleniumCommon
  3. Don't forget to restart Apache service after such changes.
Modify your code
  1. Finally, you need to configure the code for your tests to execute the selenium prepend file.
    In your class that extends PHPUnit_Extensions_SeleniumTestCase add the next property:
    protected $coverageScriptUrl = 'http://localhost/phpunit/phpunit_coverage.php';

Back to the list of entries