Two kinds of PHPUnit test carry most of the weight in custom Drupal module work: unit tests and kernel tests. They look alike. Both extend a base class, both use the same assertions, and both run from the same vendor/bin/phpunit. They answer different questions, though, and the choice decides both how fast the suite runs and which bugs it can see.
This article explains what each kind catches, what each needs, and how we choose, using tests adapted from our own site's modules. The examples target Drupal 11.4 and PHPUnit 11, and use PHPUnit's attributes rather than doc-comment annotations.
Two questions, two kinds of test
A unit test asks: given these inputs, does this class do the right thing? It runs plain PHP. No Drupal kernel boots, UnitTestCase even clears any container a previous test left behind, and there is no database and no module system. If the class needs a collaborator, the test hands it a mock.
A kernel test asks: does this code do the right thing inside Drupal? KernelTestBase boots a minimal Drupal with the modules you list, a real service container, working hooks and a real database. There is no browser; functional tests cover that, and this article leaves them aside.
The trade is speed against realism. A unit test costs little more than calling the code. A kernel test builds a container and creates tables for every test method, and each test runs in its own PHP process. That makes it much slower per test, and it is the only one of the two that sees what Drupal does with your data.
A unit test for a pure class
The best candidate for a unit test is a class with no Drupal in it. Ours is a value object: one article's translation, read from a file that ships with the code. Its constructor refuses anything that could not become a sound page.
namespace Drupal\my_module\Editorial;
final readonly class Translation {
public function __construct(
public string $uuid,
public string $langcode,
public string $title,
public string $alias,
public string $body,
) {
if (preg_match('/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/', $uuid) !== 1) {
throw new \InvalidArgumentException(sprintf('"%s" is not a UUID.', $uuid));
}
if (preg_match('/^[a-z]{2}$/', $langcode) !== 1) {
throw new \InvalidArgumentException(sprintf('"%s" is not a language code.', $langcode));
}
if (preg_match('#^(/[a-z0-9]+(-[a-z0-9]+)*)+$#', $alias) !== 1) {
throw new \InvalidArgumentException(sprintf('"%s" is not an address.', $alias));
}
foreach (['title' => $title, 'body' => $body] as $name => $text) {
if (trim($text) === '') {
throw new \InvalidArgumentException(sprintf('The translation has no %s.', $name));
}
}
}
}
Because the class depends on nothing, its test needs nothing either. A data provider lists every way a translation can be wrong, one named case each:
namespace Drupal\Tests\my_module\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\my_module\Editorial\Translation;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
#[CoversClass(Translation::class)]
final class TranslationTest extends UnitTestCase {
private const array VALID = [
'uuid' => '0b6e1f3a-52c4-4d8e-9a71-3c5d7e9f1a2b',
'langcode' => 'hu',
'title' => 'Cím',
'alias' => '/cikkek/cim',
'body' => '<p>Szöveg.</p>',
];
public function testValidTranslationIsAccepted(): void {
$this->assertSame('/cikkek/cim', (new Translation(...self::VALID))->alias);
}
#[DataProvider('unsoundTranslations')]
public function testUnsoundTranslationIsRefused(array $change): void {
$this->expectException(\InvalidArgumentException::class);
new Translation(...($change + self::VALID));
}
public static function unsoundTranslations(): array {
return [
'a node id instead of a UUID' => [['uuid' => '19']],
'a language name' => [['langcode' => 'hungarian']],
'an address with accents' => [['alias' => '/cikkek/csendes-kiadások']],
'an address without a leading slash' => [['alias' => 'cikkek/cim']],
'an empty title' => [['title' => ' ']],
'an empty text' => [['body' => '']],
];
}
}
A few things to notice. The provider is public static and takes no arguments; PHPUnit 11 refuses a provider that is not. Each case is named for what it breaks, so a failure reads like a sentence. Each case changes one value of a valid set, and a separate test proves that set really is valid, so a refusal can only come from the rule the case names. The spread with string keys passes named arguments, which keeps the cases readable. Doc-comment annotations such as @dataProvider still work in PHPUnit 11 but are deprecated and stop working in PHPUnit 12, so use the attributes.
Plugins, mocks and what they cannot see
Plenty of Drupal code is nearly pure. A text filter plugin with no injected services is a good example: you can build it with new and call process() directly, with no plugin manager involved. Here the filter highlights code blocks:
// Same namespace and imports as TranslationTest, plus:
use Drupal\my_module\Plugin\Filter\CodeBlockFilter;
#[CoversClass(CodeBlockFilter::class)]
final class CodeBlockFilterTest extends UnitTestCase {
public function testMarkupInsideABlockStaysText(): void {
$html = $this->process('<pre><code><script>alert(1)</script></code></pre>');
$this->assertStringNotContainsString('<script>', $html);
}
public function testTextWithoutBlocksIsUnchanged(): void {
$text = '<p>Run <code>drush cr</code> after the change.</p>';
$this->assertSame($text, $this->process($text));
}
private function process(string $text): string {
$filter = new CodeBlockFilter([], 'my_module_code_block', ['provider' => 'my_module']);
return (string) $filter->process($text, 'en');
}
}
The third constructor argument is the plugin definition, and FilterBase reads provider from it, so that key is required. process() returns a FilterProcessResult, which casts to the processed text.
When a class takes Drupal objects, a unit test has to mock them, and a mock does only what you configured. One case is worth knowing. Code that reads a field with the null-coalescing operator, $body->value ?? '', does not go straight to __get(). PHP asks __isset() first, an unconfigured mock answers no, and the code sees the default even though __get() was stubbed:
use Drupal\Core\Field\FieldItemListInterface;
final class ReadingTime {
public function minutes(FieldItemListInterface $body): int {
$words = str_word_count(strip_tags($body->value ?? ''));
return max(1, (int) ceil($words / 200));
}
}
// In ReadingTimeTest:
public function testMinutesComeFromTheBody(): void {
$body = $this->createMock(FieldItemListInterface::class);
$body->method('__get')->with('value')->willReturn(str_repeat('word ', 400));
// `??` asks __isset() before __get(); without this line the class sees ''.
$body->method('__isset')->with('value')->willReturn(TRUE);
$this->assertSame(2, (new ReadingTime())->minutes($body));
}
Stub both. Better still, pass the string instead of the field list when you can, and the class stays pure with nothing to mock. The case also shows the general limit of mocks: a test built on them checks your code against your picture of Drupal, not against Drupal itself.
What a kernel test needs
A kernel test needs a database. Set SIMPLETEST_DB to a database URL for the test process; without it, setup throws and no kernel test runs. Use a disposable database that belongs to no application, and keep its credentials in the environment rather than in a committed phpunit.xml. On Drupal 11, SQLite qualifies only from version 3.45, so check the version your PHP ships before relying on it.
export SIMPLETEST_DB='mysql://USER:PASS@HOST:3306/DB'
vendor/bin/phpunit -c phpunit.xml web/modules/custom/my_module/tests/src/Unit
vendor/bin/phpunit -c phpunit.xml web/modules/custom/my_module/tests/src/Kernel
vendor/bin/phpunit -c phpunit.xml --group my_module
Our root phpunit.xml bootstraps through web/core/tests/bootstrap.php, discovers every *Test.php under web/modules/custom, and is strict: risky tests, warnings and tests that assert nothing all fail the run. That strictness helps most with kernel tests, where a test can do all its setup and still check nothing. A green result with no assertions proves nothing, and the configuration makes sure you never get one.
The test then declares what it needs, and only that:
namespace Drupal\Tests\my_module\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\my_module\Editorial\Translation;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeInterface;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
#[Group('my_module')]
#[RunTestsInSeparateProcesses]
final class TranslationInstallerTest extends KernelTestBase {
private const string UUID = '0b6e1f3a-52c4-4d8e-9a71-3c5d7e9f1a2b';
protected static $modules = [
'system', 'user', 'node', 'field', 'text', 'filter', 'language',
'content_translation', 'path', 'path_alias', 'my_module',
];
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('node');
$this->installEntitySchema('path_alias');
$this->installSchema('node', ['node_access']);
$this->installConfig(['system', 'filter', 'language']);
ConfigurableLanguage::createFromLangcode('hu')->save();
NodeType::create(['type' => 'article', 'name' => 'Article'])->save();
FieldStorageConfig::create(['entity_type' => 'node', 'field_name' => 'body', 'type' => 'text_with_summary'])->save();
FieldConfig::create(['entity_type' => 'node', 'field_name' => 'body', 'bundle' => 'article', 'label' => 'Body', 'translatable' => TRUE])->save();
ContentLanguageSettings::loadByEntityTypeBundle('node', 'article')
->setThirdPartySetting('content_translation', 'enabled', TRUE)
->save();
}
Since Drupal 11.3, kernel test classes are expected to carry #[RunTestsInSeparateProcesses]. Leaving it off triggers a deprecation, and from Drupal 12 it throws an exception. The modules in $modules are loaded, not installed: their services and hooks work, but their tables and default configuration do not exist until you ask for them. Dependencies are not resolved for you either, so list every module the code touches.
Then install exactly the schema the test uses. installEntitySchema() creates an entity type's tables, installSchema() creates a module's plain tables, and installConfig() imports a module's default configuration. Here node_access is needed because re-saving a node rewrites its access grants, and adding a translation re-saves the node. A missing table shows up as a database error that names it, which tells you what to add. Installing less keeps each test quicker and its intent visible.
What only a kernel test can see
Some behavior is not in your code at all. It comes from Drupal acting on your data, and a unit test has no Drupal to act. Three kinds come up all the time.
Entity translations. Whether a field is translatable, whether a translation keeps its own value, and whether saving one language leaves the others alone are decided by field configuration and entity storage. Path aliases. The path field stores an alias per language, as a separate entity, when the node is saved. Our installer service adds a translation, unpublished for review, with its own address, so the test checks both languages:
public function testTranslationGetsItsOwnTextAndAddress(): void {
$this->assertTrue($this->installHungarian());
$node = $this->reload();
$this->assertSame('Csendes kiadások', $node->getTranslation('hu')->label());
$this->assertFalse($node->getTranslation('hu')->isPublished());
$this->assertSame('English text.', $node->getUntranslated()->get('body')->value);
$aliases = $this->container->get('path_alias.manager');
$aliases->cacheClear();
$this->assertSame('/cikkek/csendes-kiadasok', $aliases->getAliasByPath('/node/' . $node->id(), 'hu'));
$this->assertSame('/insights/quiet-releases', $aliases->getAliasByPath('/node/' . $node->id(), 'en'));
}
private function installHungarian(): bool {
Node::create([
'type' => 'article', 'uuid' => self::UUID, 'langcode' => 'en', 'status' => 1,
'title' => 'Quiet releases',
'body' => ['value' => 'English text.', 'format' => 'plain_text'],
'path' => ['alias' => '/insights/quiet-releases'],
])->save();
$translation = new Translation(self::UUID, 'hu', 'Csendes kiadások', '/cikkek/csendes-kiadasok', '<p>Magyar szöveg.</p>');
return $this->container->get('my_module.translation_installer')->install($translation);
}
private function reload(): NodeInterface {
$storage = $this->container->get('entity_type.manager')->getStorage('node');
$storage->resetCache();
return current($storage->loadByProperties(['uuid' => self::UUID]));
}
Notice reload(): it resets the storage's static cache, so the assertions read what was stored rather than an object still in memory. The alias manager has its own cache, cleared the same way. Without those two lines, a test can pass on data that never reached the database.
Access. Whether a user may see an entity depends on permissions, roles, the status of each translation and any module that adds grants. A kernel test checks the real answer. One default deserves attention: unless a test says otherwise, a kernel test that lives outside core treats user 1 as a super user, and in a fresh test database the first user you create gets that id. Turn the policy off, or your first test user bypasses every access check you meant to test:
// Added to TranslationInstallerTest from above.
use Drupal\Tests\user\Traits\UserCreationTrait;
final class TranslationInstallerTest extends KernelTestBase {
use UserCreationTrait;
protected bool $usesSuperUserAccessPolicy = FALSE;
public function testUnreviewedTranslationIsHidden(): void {
$this->installHungarian();
$node = $this->reload();
$reader = $this->createUser(['access content']);
$this->assertTrue($node->access('view', $reader));
$this->assertFalse($node->getTranslation('hu')->access('view', $reader));
}
}
The two assertions differ only in language. That difference lives in a translatable status field and in node access, which is exactly what a unit test cannot reach.
How we choose
- Put the logic in a pure class first. Rules, parsing, validation and formatting belong in classes that take plain values. They get unit tests with data providers, as many cases as the rule deserves, at almost no cost.
- Use a kernel test when the behavior depends on Drupal. Entity storage, translations, aliases, access, configuration, services and hooks all need one. A few kernel tests that prove the wiring are worth more than many mocks that imitate it.
- Mock only thin seams. If a unit test needs a long chain of mocks, the class is doing Drupal's job and the test is describing Drupal. Move that part behind a kernel test, or pass values in instead.
- Check the result, not just the color. Count assertions and skips. A suite in which every test was skipped still exits green and has proven nothing.
Limits of both
Neither kind of test drives a browser. A form's full flow as a visitor sees it, a themed page or anything that depends on JavaScript belongs to functional tests built on BrowserTestBase or WebDriverTestBase, which cost more again. Kernel tests also start from an empty site, so they prove behavior, not your production configuration; a missing permission in exported config will not show up in a test that grants it. And a unit test is only as good as its inputs: if the data provider reflects your assumptions about Drupal rather than Drupal's behavior, a kernel test is the place to confirm them.
Tests like these are part of how we keep long-lived sites easy to change. For the checks we run on someone else's code, see how we evaluate a Drupal module before it reaches your site. If you would like help adding a test suite to an existing project, see our support service.
