Testing a Drupal module

Last updated on
13 September 2023

If you have been following this practical guide to building basic Drupal 8 modules from the beginning, we are now ready for some QA. If you just want to jump right in and play along you can grab the Lorum ipsum module directly from Drupal.

Let's check that the module works as expected by writing a few tests of our own.

/tests/src/Functional/LoremIpsumTest.php

<?php

namespace Drupal\Tests\loremipsum\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests for the Lorem Ipsum module.
 * @group loremipsum
 */
class LoremIpsumTests extends BrowserTestBase {

  /**
   * Modules to install
   *
   * @var array
   */
  protected static $modules = array('loremipsum');
  protected $defaultTheme = 'stark';

  // A simple user
  private $user;

  // Perform initial setup tasks that run before every test method.
  public function setUp(): void {
    parent::setUp();
    $this->user = $this->DrupalCreateUser(array(
      'administer site configuration',
      'generate lorem ipsum',
    ));
  }

Testing begins by extending the BrowserTestBase class. It's important to note that Drupal runs tests in a testing database, which is created, populated as needed and then destroyed. This means that you can test on several different testing environments without changing the contents of your database.

The first order of business for tests, as you can see above, is to perform some initial setup by defining the modules to test (just the present one), creating a test user and giving it the required permissions.

Then we test access to the dummy text generation page:

  /**
   * Tests that the Lorem ipsum page can be reached.
   */
  public function testLoremIpsumPageExists() {
    // Login
    $this->drupalLogin($this->user);

    // Generator test:
    $this->drupalGet('loremipsum/generate/4/20');
    $this->assertSession()->statusCodeEquals(200);
  }

And the config form:

  /**
   * Tests the config form.
   */
  public function testConfigForm() {
    // Login
    $this->drupalLogin($this->user);

    // Access config page
    $this->drupalGet('admin/config/development/loremipsum');
    $this->assertSession()->statusCodeEquals(200);
    // Test the form elements exist and have defaults
    $config = \Drupal::config('loremipsum.settings');
    $this->assertSession()->fieldValueEquals(
      'page_title',
      'Lorem ipsum'
    );
    $source_text = 'Lorem ipsum dolor sit amet, consectetur adipisci elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' . PHP_EOL;
    $source_text .= 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ' . PHP_EOL;
    $source_text .= 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ' . PHP_EOL;
    $source_text .= 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ';
    $this->assertSession()->fieldValueEquals(
      'source_text',
      $source_text
    );

Next we test the config form can be submitted:

    // Test form submission
    $this->submitForm(
      [
        'page_title' => 'Test lorem ipsum',
        'source_text' => 'Test phrase 1 \nTest phrase 2 \nTest phrase 3 \n',
      ],
      t('Save configuration'),
    );
    $this->assertSession()->responseContains(
      'The configuration options have been saved.',
      'The form was saved correctly.'
    );

And assert that the new values are there:

    // Test the new values are there.
    $this->drupalGet('admin/config/development/loremipsum');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->fieldValueEquals(
      'page_title',
      'Test lorem ipsum'
    );
    $this->assertSession()->fieldValueEquals(
      'source_text',
      'Test phrase 1 \nTest phrase 2 \nTest phrase 3 \n'
    );
  }

Testing complexity

Please note this is only one of the many different types of test you can execute on your code. Familiarize yourself with different test types covered by Drupal, and you'll be able to incorporate them into your workflow. More info can be found in the Automated testing guide.

Running tests

You'll need to optimize your local development environment in order to properly run tests. Here's a guide for running PHPUnit under Lando.

Wrapping up

And that's it for this tutorial! If you want, grab a copy of this code at the Lorem ipsum project page. If you have any questions, feel free to drop me a line. Happy coding!

Help improve this page

Page status: No known problems

You can: