Writing custom assertions in your tests

Writing custom assertions is a great way to clean up your test code.

Here's an example from one of my client Drupal projects:

private static function assertProductVariationHasPrice(ProductVariationInterface $productVariation, string $expectedPrice): void {
  self::assertSame(
    actual: $productVariation->getPrice()->getNumber(),
    expected: $expectedPrice,
  );
}

This one wraps a single assertion, but they could also include multiple assertions or additional steps.

Here's the thing

A custom assertion is a simple function but it makes the test code more readable and less repetitive.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.