🇬🇧 How to Write Your First Functional Test in Drupal 10

How to Write Your First Functional Test in Drupal 10

Learn how to create and run a simple functional test in Drupal 10 using PHPUnit and DDEV. This step-by-step tutorial covers everything from file structure to execution and output.

web/
└── modules/
    └── custom/
        └── my_module/
            ├── my_module.info.yml
            ├── my_module.module
            └── tests/
                └── Functional/
                    └── HelloWorldTest.php

🧑‍💻 1. Create the Test File

Path:

web/modules/custom/my_module/tests/Functional/HelloWorldTest.php

Content:

<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Verifies that the homepage loads successfully.
 *
 * @group my_module
 */
class HelloWorldTest extends BrowserTestBase {

  /**
   * The default theme used for the test.
   */
  protected $defaultTheme = 'stark';

  /**
   * Modules required to run this test.
   */
  protected static $modules = ['node'];

  /**
   * Check that the home page returns a 200 response.
   */
  public function testHomePageLoads() {
    $this->drupalGet('<front>');
    $this->assertSession()->statusCodeEquals(200);
  }

}

⚙️ 2. Install development dependencies

Make sure phpunit and test support are available. Run this from your root project:

composer require --dev drupal/core-dev

⚒️ 3. Create PHPUnit config file

cp web/core/phpunit.xml.dist phpunit.xml

🚀 4. Run the Test

Use this full command:

ddev exec bash -c 'SIMPLETEST_BASE_URL="http://drupal10.ddev.site" BROWSERTEST_OUTPUT_DIRECTORY="/var/www/html/web/sites/simpletest" ./vendor/bin/phpunit -c web/core web/modules/custom/my_module/tests/Functional'

🧪 SIMPLETEST_BASE_URL It is The base URL of your Drupal site, as seen by the test browser (e.g. DDEV). In DDEV, it’s usually http://.ddev.site.

📂 BROWSERTEST_OUTPUT_DIRECTORY Where Drupal stores test artifacts, like HTML output, screenshots, and debug info. Must be writable. Common path: /var/www/html/web/sites/simpletest.

✅ 5. Expected Output

PHPUnit 9.6.23 by Sebastian Bergmann and contributors.

Testing /var/www/html/web/modules/custom/my_module/tests/Functional
.                                                                   1 / 1 (100%)

Time: 00:01.384, Memory: 8.00 MB

OK (1 test, 3 assertions)

HTML output was generated
http://drupal10.ddev.site/sites/simpletest/browser_output/Drupal_Tests_my_module_Functional_HelloWorldTest-0-XXXX.html

yay congratulations it is working as expected.


© 2024. All rights reserved.