Concepts of Unit Testing in Drupal 9 with Example

29 / Aug / 2023 by Anurag Nagar 0 comments

Introduction

In the realm of Drupal 9 development, ensuring the dependability and stability of your applications stands as a paramount objective. The practice of unit testing emerges as a potent strategy to achieve this goal, allowing developers to validate individual building blocks of their codebase. This comprehensive guide takes a deep dive into the intricacies of unit testing within the Drupal 9 context, providing practical examples that underscore its importance.

Grasping the essence of unit testing and its implications

In the dynamic world of software development, unit testing plays a pivotal role by breaking down code into manageable units for targeted evaluation. These discrete tests hold the power to unearth latent bugs, thereby promoting software reliability and performance. In the context of Drupal 9, these units can be functions, methods, or services, forming the bedrock of quality assurance.

Configuring your local Drupal 9 environment for seamless unit testing

Before embarking on your unit testing journey, a local development environment equipped with PHPUnit and the “Drupal Test Traits” Composer package is indispensable. This toolkit, comprising traits and utilities tailored to Drupal testing, lays the foundation for effective unit testing. Ensure a smooth installation and alignment of PHPUnit with the package.

Crafting your maiden Drupal 9 unit test

Let’s illustrate the concept with a scenario: Imagine a custom module containing a function that calculates the sum of two numbers. A simple yet illustrative unit test might look like this:

namespace Drupal\Tests\test_module\Unit;
use Drupal\Tests\UnitTestCase; 
use Drupal\test_module\Calculator; 

/** 
* Testing the Calculator class. 
*
* @group test_module 

*/ 
class CalculatorTest extends UnitTestCase{ 
public function testSum() { 
$calculator = new Calculator(); 
$this->assertEquals(5, $calculator->sum(2, 3)); 
} 
}

Probing Deeper: Unveiling the secrets of testing Drupal services

The architecture of Drupal relies extensively on services. Delving into service testing, we leverage the “Container” trait, a gem from the “Drupal Test Traits” package. This example illustrates creating a service instance:

namespace Drupal\Tests\test_module\Unit; 

use Drupal\Tests\UnitTestCase; 
use Drupal\test_module\MyService; 
use Drupal\Core\DependencyInjection\ContainerBuilder; 
use Drupal\Core\DependencyInjection\Container; 

/** 
* Testing the MyService class. 
* 
* @group test_module */ 

class MyServiceTest extends UnitTestCase { 
protected function setUp(): void { 
parent::setUp(); 
$this->container = new Container(new ContainerBuilder()); 


public function testSomething() { 
 $my_service = new MyService($this->container); 
 $result = $my_service->doSomething(); 
 $this->assertEquals('expected_result', $result); 
 } 
}
namespace Drupal\Tests\test_module\Unit; 

use Drupal\Tests\UnitTestCase; 
use Drupal\test_module\MyService; 
use Prophecy\Prophet; 

/** 
 * Testing the MyService class. 

 * @group test_module */ 
class MyServiceTest extends UnitTestCase { 

public function testSomething() { 
   $prophet = new Prophet(); 
   $dependency = $prophet->prophesize(AnotherService::class);
   $dependency->someMethod()->willReturn('mocked_result');

   $my_service = new MyService($dependency->reveal()); 
   $result = $my_service->doSomething(); 
   $this->assertEquals('expected_result', $result); 

   $prophet->checkPredictions(); 

}

Embracing diverse scenarios with data providers

Enhancing testing coverage is achievable through data providers. This technique enables tests to run with various inputs, effectively broadening their scope:

namespace Drupal\Tests\test_module\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\test_module\Calculator;

/**
* Testing the Calculator class.
*
* @grouptest_module
*/ class CalculatorTest extends UnitTestCase{

/**
* @dataProvider sumDataProvider
*/ public function testSum($a, $b, $expected) { $calculator = new Calculator();
 $this->assertEquals($expected, $calculator->sum($a, $b));
 }
public function sumDataProvider() { return [ [2, 3, 5], [0, 0, 0], [-1, 1, 0], ];
}
}

Navigating the execution and Analysis of unit tests

Execute your tests with the command

phpunit -c web/core web/modules/custom/test_module/tests/src/Unit,

Where web/core denotes the Drupal core directory, PHPUnit streamlines the identification of passed and failed tests, expediting issue resolution.

In Conclusion

Elevating code integrity through thoughtful unit testing

The realm of unit testing in Drupal 9 empowers developers to build robust applications of enduring quality. By scrutinizing discrete code units meticulously, latent defects are unearthed, paving the way for preemptive remediation. With the synergistic interplay of PHPUnit and the “Drupal Test Traits” package, the embrace of unit testing within the Drupal ecosystem emerges as a transformative endeavor.

If you have any questions, please feel free to reach out via comments.

 

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *