Setup PHPUnit for Drupal 8/9

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit architecture for unit testing frameworks that originated with SUnit and became popular with JUnit. PHPUnit was created by Sebastian Bergmann and its development is hosted on GitHub.

In this example, we are going to setup PHP Unit for Drupal 8/9 projects, so let's create a vanilla Drupal project with the recommended template.

  • Create a Drupal project with composer using the recommended template.

    composer create-project drupal/recommended-project drupal-test
    cd drupal-test
    composer require drupal/core-dev
  • Download and install Chromedriver
  • Export the following variables in your terminal session:

    export SIMPLETEST_DB='mysql://user:password@localhost/db_name'
    export SIMPLETEST_BASE_URL=http://127.0.0.1:8080
    export BROWSERTEST_OUTPUT_DIRECTORY="sites/simpletest/browser_output"
    
  • Run chromedriver if you are running JavaScript functional tests.

    export MINK_DRIVER_ARGS_WEBDRIVER='["chromedriver", null, "http://localhost:4444"]'
    chromedriver --port=4444
  • Run a PHP development server using the drush command to execute the tests:

    drush runserver 8080
  • For example, execute your test from the project web directory (document root).

    ../vendor/bin/phpunit -c core --debug modules/custom/module_name/tests/src/FunctionalJavascript/SomeTest.php
    
  • In order to run a specific function from a test, use the filter parameter.

    ../vendor/bin/phpunit -c core --debug modules/custom/module_name/tests/src/FunctionalJavascript/SomeTest.php --filter=functionName
    

 

0/5