Simpletest Class, File, and Namespace structure

Last updated on
25 July 2018

This page has not yet been reviewed by Automated testing maintainer(s) and added to the menu.

This documentation is deprecated.

NOTE: As of Drupal 8 simpletest is deprecated, please use phpunit tests, see https://www.drupal.org/docs/8/phpunit

In Drupal 8, Simpletest tests have to have a specific namespace, file, and class structure in order to be recognized by the testing framework.

Tests of Core functionality

Tests for code under core/lib/Drupal/Component should be done using PHPUnit, not SimpleTest. These classes do not depend on Drupalisms (hooks, etc.), the Drupal database, or even having a Drupal site instantiated. See https://www.drupal.org/phpunit for information.

Tests for code under core/lib/Drupal/Core can be done with SimpleTest, although if possible, PHPUnit tests with mock inputs are preferred. If you are writing a Simpletest test for one of these classes, treat it as if it was a test for the System module.

Tests of Modules

Simpletest tests for any module belong in the \Drupal\(modulename)\Tests namespace, and therefore (following the PSR-4 file convention for PHP classes), they go in .php files under (module directory)/src/Tests. These can be organized into sub-directories if desired. For example, the core System module is in core/modules/system, so its Simpletest tests are in subdirectories of core/modules/system/src/Tests.

Here's an example of one of these test files (core/modules/system/src/Tests/Pager/PagerTest.php, showing just the essential parts of the file and minus the actual test code):

/**
 * @file
 * Contains \Drupal\system\Tests\Pager\PagerTest.
 */

namespace Drupal\system\Tests\Pager;

use Drupal\simpletest\WebTestBase;

/**
 * Tests pager functionality.
 *
 * @group Pager
 */
class PagerTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('dblog', 'pager_test');

  /**
   * Tests markup and CSS classes of pager links.
   */
  public function testActiveClass() {
    // Any public method whose name starts with "test" is a test that will be executed.
  }

}

Notes:

  • Extend WebTestBase for tests that require a browser.
  • $modules gives a list of the modules to enable for the test.
  • The @group line in the class doc block tells what group in the Testing module UI the test will appear in. [The @group annotations are really important]
  • The first line of the class doc block gives the description of the test that will appear in the Testing module UI

Help improve this page

Page status: Deprecated

You can: