WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Writing a basic unit test and a basic functional test in Drupal 8

Submitted by barnettech on Mon, 05/11/2020 - 09:23

in a custom module setup a directory structure as such: tests/src/Unit/SkeletonTest.php Call the test and the php file anything you like, then the file contains the following (this is a most basic test obviously):

Run all the tests for a module with

 ../vendor/phpunit/phpunit/phpunit -c core/ ./modules/custom/entity_sync/ 
<?php

// @TODO Add namespace

namespace Drupal\Tests\entity_sync\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\enity_sync;

/**
 * Skeleton functional test.
 *
 * @group testing_examples
 */
class SkeletonTest extends UnitTestCase {

  public function testOneEqualsOne() {
    $this--->assertEquals(
      1, 1
    );


  }

}

also this functional test works after in the core directory renaming phpunit.xml.dist to phpunit.xml and then it should look like what is described in this article: https://www.drupal.org/docs/8/testing/phpunit-in-drupal-8/running-phpun…




  
  
  
  
  
  
  
  
  
  
 

<?php

namespace Drupal\Tests\hello_world\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Test basic functionality of My Module.
 *
 * @group hello_world
 */
class BasicTestCase extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    // Module(s) for core functionality.
    'node',
    'views',

    // This custom module.
    'hello_world',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    // Make sure to complete the normal setup steps first.
    parent::setUp();

    // Set the front page to "node".
    \Drupal::configFactory()
      ->getEditable('system.site')
      ->set('page.front', '/node')
      ->save(TRUE);
  }

  /**
   * Make sure the site still works. For now just check the front page.
   */
  public function testTheSiteStillWorks() {
    // Load the front page.
    $this->drupalGet('/hello/world');

    // Confirm that the site didn't throw a server error or something else.
    //$this->assertSession()->statusCodeEquals(200);

    // Confirm that the front page contains the standard text.
    $this->assertText('Saying Hello World in Drupal 8 is cool!');
  }

}