Loading...

HOW TO WRITE YOUR FIRST TEST CASE USING PHPUNIT & KERNEL IN DRUPAL


Introduction

Writing test cases is crucial for ensuring the stability and reliability of your Drupal project. In this guide, we'll explore how to write your first test case using PHPUnit and the Kernel test framework in Drupal.

Setting Up Environment

Before writing test cases, you need to set up a suitable environment:

  • Ensure you have PHPUnit installed on your system.
  • Create a test module or use an existing module in your Drupal project.
  • Set up a testing database and configure your Drupal installation to use it.

Writing Your First Test Case

Now, let's write a simple test case to check if a basic functionality works:


namespace Drupal\Tests\your_module\Kernel;

use Drupal\KernelTests\KernelTestBase;

/**
 * Tests for the functionality of your_module.
 *
 * @group your_module
 */
class YourModuleTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'your_module',
  ];

  /**
   * Tests your_module functionality.
   */
  public function testYourModuleFunctionality() {
    // Your test logic goes here.
    // Example:
    $this->assertTrue(TRUE, 'Test case executed successfully.');
  }

}
            

Running Tests

To run your tests, execute the following command in your Drupal project root directory:


./vendor/bin/phpunit -c core --testsuite=your_module
            

PHPUnit Tests

Setting up PHPUnit in Drupal:


$ composer require --dev phpunit/phpunit --with-dependencies
$ composer require behat/mink && composer require --dev phpspec/prophecy
            

Setting up PHPUnit with Lando:


$ sed -i 's|tests\/bootstrap\.php|/app/web/core/tests/bootstrap.php|g' phpunit.xml
$ lando rebuild -y
$ lando test core/modules/datetime/tests/src/Unit/Plugin/migrate/field/DateFiedTest.php
            

Kernel Tests

Writing your first Kernel Test:


namespace Drupal\Tests\events_example\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\events_example\EventSubscriber\EventsExampleSubscriber;

/**
 * Test to ensure 'events_example_subscriber' service is reachable.
 *
 * @group events_example
 *
 * @ingroup events_example
 */
class EventsExampleServiceTest extends KernelTestBase {

 /**
  * {@inheritdoc}
  */
 protected static $modules = ['events_example'];

 /**
  * Test for existence of 'events_example_subscriber' service.
  */
 public function testEventsExampleService() {
   $subscriber = $this->container->get('events_example_subscriber');
   $this->assertInstanceOf(EventsExampleSubscriber::class, $subscriber);
 }

}
            

Additional Resources

Here are some additional resources to help you learn more about testing in Drupal: