Drupalwoo ☉

How to write a Drupal unit test for a custom service

A custom Drupal service usually contains a small piece of business logic that should work independently of a page, form, controller, or database. A unit test verifies that logic in isolation, so a failure points towards the service rather than an entire web request.

This approach is useful when a module calculates delivery estimates, transforms API data, applies editorial rules, or validates a workflow. For example, an Australian commerce site might treat Sydney, Melbourne, and Brisbane postcodes differently from a regional Western Australia address. Those rules can be tested quickly without opening a browser or creating Drupal content.

Drupal’s PHPUnit tooling provides the test base classes, mocks, and assertions needed for this work. If your module also includes front-end assets, keep that concern separate from the service test; the Webpack bundling checklist covers a different part of the module development workflow.

Decide what the service must prove

Begin with the service’s observable behaviour. A useful unit test should answer a specific question such as, “Does a postcode in the Sydney metropolitan area receive the expected delivery estimate?” It should not attempt to prove that Drupal can discover the service, that YAML syntax is valid, and that an HTTP request renders correctly in the same test.

The example below uses a DeliveryEstimate service. It accepts a four-digit Australian postcode and returns a business-day estimate. The rule is deliberately simple: metropolitan Sydney postcodes receive one day, Melbourne and Brisbane receive two, and other valid postcodes receive five. Orders placed after 2 pm receive an extra business day.

Create the class at src/Service/DeliveryEstimate.php:

<?php

namespace Drupal\shipping_rules\Service;

use Drupal\Component\Datetime\TimeInterface;
use InvalidArgumentException;

final class DeliveryEstimate {

  public function __construct(
    private readonly TimeInterface $time,
  ) {}

  public function forPostcode(string $postcode): string {
    if (!preg_match('/^\d{4}$/', $postcode)) {
      throw new InvalidArgumentException('A four-digit postcode is required.');
    }

    $prefix = (int) substr($postcode, 0, 2);

    $days = match (TRUE) {
      $prefix >= 20 && $prefix <= 22 => 1,
      $prefix >= 30 && $prefix <= 32 => 2,
      $prefix >= 40 && $prefix <= 41 => 2,
      default => 5,
    };

    if ((int) gmdate('G', $this->time->getCurrentTime()) >= 14) {
      $days++;
    }

    return sprintf('%d business days', $days);
  }

}

The service has one dependency: Drupal’s TimeInterface. Injecting time is important because a direct call to time() would make the result change whenever the test runs. A fixed clock lets the test control the current hour and makes the business rule deterministic.

Keep the service easy to isolate

A unit test is most effective when the class under test has clear inputs, predictable outputs, and small dependencies. Constructor injection makes those dependencies visible. It also means the test can provide a mock clock rather than booting Drupal’s complete service container.

Register the service in shipping_rules.services.yml:

services:
  shipping_rules.delivery_estimate:
    class: Drupal\shipping_rules\Service\DeliveryEstimate
    arguments:
      - '@datetime.time'

The service definition belongs to the module’s integration configuration, while the unit test focuses on the PHP class. This separation matters when debugging a failed build on a local machine in Brisbane or in a hosted environment in Sydney: a service wiring problem and a calculation problem should produce different tests and different failures.

Avoid calling global Drupal helpers directly from business logic where possible. Static calls to configuration, the current user, the database, or the clock make isolation harder. Inject an interface instead. For a more involved service, you might inject a repository interface, a logger, or a configuration factory and replace each dependency with a test double.

Create the PHPUnit test class

Drupal module tests commonly live under tests/src/Unit. For this service, create modules/custom/shipping_rules/tests/src/Unit/Service/DeliveryEstimateTest.php. The namespace mirrors the test directory, and the class extends Drupal’s UnitTestCase.

<?php

namespace Drupal\Tests\shipping_rules\Unit\Service;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\shipping_rules\Service\DeliveryEstimate;
use Drupal\Tests\UnitTestCase;
use InvalidArgumentException;

final class DeliveryEstimateTest extends UnitTestCase {

  private TimeInterface $clock;
  private DeliveryEstimate $service;

  protected function setUp(): void {
    parent::setUp();

    $this->clock = $this->createMock(TimeInterface::class);
    $this->service = new DeliveryEstimate($this->clock);
  }

  public function testSydneyPostcodeBeforeCutOff(): void {
    $this->clock
      ->method('getCurrentTime')
      ->willReturn(strtotime('2025-02-10 10:00:00 UTC'));

    $this->assertSame(
      '1 business days',
      $this->service->forPostcode('2000'),
    );
  }

}

setUp() runs before each test method, so every test receives a fresh mock and a fresh service instance. The createMock() method is supplied by PHPUnit through Drupal’s test base class. The mock does not contact a real clock; it returns the timestamp configured by the test.

The test method name describes the scenario and expected outcome. A name such as testSydneyPostcodeBeforeCutOff is more useful than testService, particularly when a continuous integration job reports one failure among many module tests.

Mock dependencies and cover meaningful branches

A good unit test suite covers the branches that represent real business decisions. For this service, those branches include a Sydney postcode before the cut-off, a Melbourne postcode after the cut-off, a regional postcode, and invalid input. The examples use familiar Australian values, such as postcode 3000 for Melbourne and 4000 for Brisbane.

Add these methods to the test class:

  public function testMelbournePostcodeAfterCutOff(): void {
    $this->clock
      ->method('getCurrentTime')
      ->willReturn(strtotime('2025-02-10 15:30:00 UTC'));

    $this->assertSame(
      '3 business days',
      $this->service->forPostcode('3000'),
    );
  }

  public function testBrisbanePostcodeBeforeCutOff(): void {
    $this->clock
      ->method('getCurrentTime')
      ->willReturn(strtotime('2025-02-10 09:00:00 UTC'));

    $this->assertSame(
      '2 business days',
      $this->service->forPostcode('4000'),
    );
  }

  public function testRegionalPostcodeUsesDefaultEstimate(): void {
    $this->clock
      ->method('getCurrentTime')
      ->willReturn(strtotime('2025-02-10 09:00:00 UTC'));

    $this->assertSame(
      '5 business days',
      $this->service->forPostcode('6536'),
    );
  }

  public function testInvalidPostcodeThrowsAnException(): void {
    $this->expectException(InvalidArgumentException::class);
    $this->expectExceptionMessage('A four-digit postcode is required.');

    $this->service->forPostcode('NSW');
  }

Each test controls only the dependency behaviour it needs. The clock is configured with method('getCurrentTime'), and the assertion checks the public return value. There is no assertion about private variables or implementation details, so the service can later change its internal matching logic without forcing a rewrite of every test.

The timestamp uses UTC deliberately. In production, business cut-offs may need a named Australian timezone such as Australia/Sydney or Australia/Brisbane, especially around daylight saving. If the requirement includes local time, inject a clock abstraction that returns a DateTimeImmutable in the chosen timezone and test the daylight-saving boundary explicitly.

Test type Drupal bootstrapping Typical dependencies Best use
Unit test None or minimal Mocks and value objects Pure service rules and validation
Kernel test Drupal kernel Real container and selected modules Service wiring, entity queries, configuration
Functional test Full Drupal installation Browser-like request and rendered output Forms, pages, permissions, redirects
Functional JavaScript test Browser and JavaScript Full site plus client-side runtime Interactive behaviour and browser events

Run the test with Drupal’s tooling

A project using Drupal’s recommended Composer setup normally includes PHPUnit through the drupal/core-dev dependency. From the project root, run the complete unit suite with:

vendor/bin/phpunit -c web/core/phpunit.xml.dist \
  web/modules/custom/shipping_rules/tests/src/Unit/Service/DeliveryEstimateTest.php

The exact document root may be web, docroot, or another directory depending on the project template. Use the PHPUnit configuration file that matches the project’s Drupal installation. Some teams define a project-level phpunit.xml so custom modules can be tested with a shorter command.

A successful run reports the number of tests and assertions. If PHPUnit cannot find the class, check the namespace, file path, class name, and Composer autoload configuration. If Drupal reports that TimeInterface cannot be loaded, confirm the module is being tested inside a Drupal codebase with the appropriate core dependencies installed.

Run the test after changing either the service or its test. A focused command gives rapid feedback, while a full unit-suite run catches interactions with shared test configuration. On a large Australian government or enterprise site, this fast feedback is valuable because a complete pipeline may also build configuration, run coding standards, and execute browser tests.

Know when a unit test is not enough

A unit test does not prove that Drupal discovers the service from YAML. It constructs the PHP class directly, so a typo in shipping_rules.services.yml could remain hidden. That is why service registration belongs in a kernel test when the wiring itself is part of the requirement.

A kernel test can boot Drupal, retrieve the service from the container, and confirm that its real dependency is injected. It is slower than a unit test, but it can catch an incorrect service ID, an invalid argument, missing module dependencies, or configuration that is unavailable during container compilation.

Use a functional test when the service is exercised through a form submission, controller route, access check, or rendered page. For example, if an editor in a Perth office enters a postcode into a delivery form, a functional test can verify validation messages and the final markup. Keep the calculation scenarios in the unit test so the functional test remains focused on the user-facing integration.

A practical suite often contains many small unit tests, a few kernel tests for container and entity integration, and a smaller number of functional tests for complete workflows. This balance keeps custom Drupal development dependable without making every change wait for a full browser session.