You can see some official documentation on Drupal testing to start.
See also test-driven Drupal development in the Drupal at your Fingertips book.
Writing tests is not as difficult as it seems! The first step seems to be the hardest. Let's write a single, simple test to be soundly on our way of practicing test-driven development!
But first, let's set up the environment. It's relatively simple - although to be safe, I just might have two local instances of the drupal docker setup, to not pollute my production setup with development-grade dependencies.
The dependencies are defined in composer.json and they are, phpunit, core-dev and mink. I have outlined the development-grade setup on my wiki and here it is pasted again:
composer require --dev --no-update symfony/filesystem:4.4.42
composer require --dev drupal/core-dev:9.5.11 --with-all-dependencies
composer require --dev behat/mink jcalderonzumba/mink-phantomjs-driver
composer update -W
composer update symfony/filesystem:4.4.42 drush/drush -W
composer require --dev drupal/core-dev -W
composer require --dev phpspec/prophecy-phpunit:^2You'd have a copy of phpunit.xml and edit it appropriately. Then you'll be able to run your tests:
cd /var/www/html # that's where my composer.json is
cp web/core/phpunit.xml.dist .
./vendor/bin/phpunit web/modules/ish_drupal_module/tests/src/Functional/UserProfileAnonymousAccessTest.phpNow then, let's write a test, say, assert that a user profile is view-able by an anonymous user. As suggested by GPT, and you can view the same file on github:
// modules/my_module/tests/src/Functional/UserProfileAnonymousAccessTest.php
<?php
namespace Drupal\Tests\ish_drupal_module\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Tests anonymous access to user profile pages.
*
* @group ish_drupal_module
*/
class UserProfileAnonymousAccessTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'user',
];
/**
* Test that anonymous users can view user profiles.
*/
public function testAnonymousCanViewUserProfile(): void {
// Create a user account.
$account = User::create([
'name' => 'public_user',
'mail' => 'public@example.com',
'status' => 1,
]);
$account->save();
// Grant anonymous users permission to view user information.
$anonymous_role = $this->container
->get('entity_type.manager')
->getStorage('user_role')
->load('anonymous');
$anonymous_role->grantPermission('access user profiles');
$anonymous_role->save();
// Clear caches so permission changes apply.
$this->container->get('cache_tags.invalidator')->invalidateTags(['config:user.role.anonymous']);
// Visit the user profile as anonymous.
$this->drupalGet('/user/' . $account->id());
// Assert HTTP 200.
$this->assertSession()->statusCodeEquals(200);
// Assert the page is not access denied.
$this->assertSession()->pageTextNotContains('Access denied');
// Assert username is visible.
$this->assertSession()->pageTextContains('public_user');
}
}
.
.^.