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.
Before writing test cases, you need to set up a suitable environment:
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.');
}
}
To run your tests, execute the following command in your Drupal project root directory:
./vendor/bin/phpunit -c core --testsuite=your_module
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
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);
}
}
Here are some additional resources to help you learn more about testing in Drupal: