| name | drupal-unit |
| description | Drupal Unit tests with UnitTestCase — testing isolated PHP logic with no Drupal bootstrap, mocking dependencies. |
Drupal Unit Tests
When to Use
- Pure PHP logic with no Drupal dependencies
- Utility functions, data transformations, value objects
- Classes where all dependencies can be mocked
Basic Structure
namespace Drupal\Tests\my_module\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\my_module\Service\MyService;
use Psr\Log\LoggerInterface;
final class MyServiceTest extends UnitTestCase {
private MyService $service;
protected function setUp(): void {
parent::setUp();
$logger = $this->createMock(LoggerInterface::class);
$this->service = new MyService($logger);
}
public function testProcessData(): void {
$input = ['foo' => 'bar'];
$result = $this->service->processData($input);
$this->assertArrayHasKey('processed', $result);
$this->assertTrue($result['processed']);
}
public function testProcessDataWithEmptyInput(): void {
$this->expectException(\InvalidArgumentException::class);
$this->service->processData([]);
}
}
Mocking with PHPUnit
$mock = $this->createMock(SomeInterface::class);
$mock->method('someMethod')->willReturn('value');
$mock->expects($this->once())
->method('someMethod')
->with($this->equalTo('expected-arg'))
->willReturn('result');
$mock->method('someMethod')->willThrowException(new \RuntimeException('Error'));
$mock->method('someMethod')
->willReturnMap([
['arg1', 'result1'],
['arg2', 'result2'],
]);
Mocking Drupal Translation (t())
$this->service = new MyService(
$this->getStringTranslationStub()
);
Mocking Logger
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())
->method('error')
->with($this->stringContains('Failed to process'));
Running Tests
Examples assume a docroot/-based Drupal project. If your project uses web/ or another document root, adjust paths accordingly.
ddev exec vendor/bin/phpunit docroot/modules/custom/my_module/tests/src/Unit/MyServiceTest.php
ddev exec vendor/bin/phpunit docroot/modules/custom/my_module/tests/src/Unit/
ddev exec vendor/bin/phpunit --verbose docroot/modules/custom/my_module/tests/