| name | drupal-kernel |
| description | Drupal Kernel tests with KernelTestBase — testing services, database operations, hooks, and entity operations with minimal Drupal bootstrap. |
Drupal Kernel Tests
When to Use
- Testing services that interact with Drupal's service container
- Database operations and entity CRUD
- Hook implementations
- Config operations
- Tests needing a real database but not a full browser
Basic Structure
namespace Drupal\Tests\my_module\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
final class MyServiceTest extends KernelTestBase {
protected static $modules = [
'system',
'user',
'node',
'field',
'text',
'my_module',
];
protected function setUp(): void {
parent::setUp();
$this->installSchema('system', ['sequences']);
$this->installSchema('node', ['node_access']);
$this->installEntitySchema('user');
$this->installEntitySchema('node');
$this->installConfig('my_module');
NodeType::create(['type' => 'article', 'name' => 'Article'])->save();
}
public function testServiceProcessesNode(): void {
$node = Node::create([
'type' => 'article',
'title' => 'Test Node',
'status' => 1,
]);
$node->save();
$service = $this->container->get('my_module.my_service');
$result = $service->process($node);
$this->assertTrue($result);
}
}
installEntitySchema vs installSchema
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('paragraph');
$this->installSchema('system', ['sequences', 'key_value']);
$this->installSchema('node', ['node_access']);
$this->installConfig('my_module');
$this->installConfig(['node', 'user']);
Creating Test Users
use Drupal\user\Entity\User;
$user = User::create([
'name' => 'test_user',
'mail' => 'test@example.com',
'status' => 1,
]);
$user->save();
$this->setCurrentUser($user);
Testing Config
$config = $this->config('my_module.settings');
$this->assertTrue($config->get('enabled'));
$this->config('my_module.settings')
->set('enabled', FALSE)
->save();
Testing Hooks
public function testHookNodePresave(): void {
$node = Node::create(['type' => 'article', 'title' => 'Test']);
$node->save();
$node = Node::load($node->id());
$this->assertEquals('Modified by hook', $node->get('field_processed')->value);
}