Please feel free to create issues and/or submit pull requests to this
repository whilst working through these instructions. Any contributions
would be greatly appreciated!
Feedback
--------
Feedback would also be appreciated! You can contact me via oliver@odwd.uk, [@opdavies on Twitter](https://twitter.com/opdavies) or ``opdavies`` on Drupal Slack.
Introduction
------------
Creating a new Drupal project with Composer
-------------------------------------------
If don’t have Composer, visit https://getcomposer.org/download for instructions on how to install it on your computer.
This assumes that Composer is installed globally and is available by running the ``composer`` command. Alternatively, you can download the phar file and run ``php composer.phar`` instead.
This module will be used to demonstrate how to take a test-driven
approach to develop a module to the following acceptance criteria:
- As a site visitor
- I want to see a list of all published articles at ``/blog``
- Ordered by post date, with the newest posts first
Step 0: Preparation
-------------------
To begin, we need the site to be running.
..code:: bash
# Using DDEV
ddev start
# Using PHP's web server
php -S localhost:8000 -t web
You don’t need to install Drupal. It just needs to be able to connect to
the database.
Step 1: Writing your first test
-------------------------------
1a. Create the module directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a directory for the new module:
::
mkdir -p web/modules/custom/my_module
1b. Create an ``.info.yml`` file for the module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to install the module, it needs an info.yml file that matches the name of the module (e.g. ``my_module.info.yml``).
Within the ``my_module`` directory, create the file and paste in the following content:
..code:: yaml
name: My Module
type: module
core_version_requirement: ^8 || ^9
1c. Create the directory structure for tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
..code:: bash
mkdir -p tests/src/Functional
1d. Create your first test case
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
..code:: php
<?php
namespace Drupal\Tests\my_module\Functional;
use Drupal\Tests\BrowserTestBase;
use Symfony\Component\HttpFoundation\Response;
class FrontPageTest extends BrowserTestBase {
protected static $modules = ['node', 'views'];
/** @test */
public function the_front_page_loads_for_anonymous_users() {
$this->config('system.site')
->set('page.front', '/node')
->save(TRUE);
$this->drupalGet('<front>');
$assert = $this->assertSession();
$assert->statusCodeEquals(Response::HTTP_OK);
$assert->pageTextContains('Welcome to Drupal');
$assert->pageTextContains('No front page content has been created yet.');
}
}
Some things to note:
- The name of the class must match the filename.
- The filename must end with ``Test.php``.
- The namespace is ``Drupal\Tests\{module_name}``, followed by any additional directories (e.g. ``Functional``).
- Test methods must start with ``test``, or use the ``@test`` annotation.
1e. Preparing PHPUnit
~~~~~~~~~~~~~~~~~~~~~
Firstly, we need to create a ``phpunit.xml`` file to configure PHPUnit. Core has a ``phpunit.xml.dist`` file that we can duplicate and edit.
..code:: bash
cp web/core/phpunit.xml.dist web/core/phpunit.xml
Update the ``SIMPLETEST_BASE_URL`` value to be the address that the website is currently running on. This needs to be correct so that functional tests return the correct response codes, so ensure that any port numbers are correct and also that the site is correctly marked as HTTP or HTTPS.
We also need to configure the database for Drupal to connect to and use when running functional and kernel tests. This could be your project’s MySQL or PostgreSQL database with a table prefix, but in this case, we’ll use a separate SQLite database.
To simplify running tests, the command could be simplified by `adding a script <https://getcomposer.org/doc/articles/scripts.md#writing-custom-commands>` to ``composer.json``:
This means that you can run just ``ddev composer test:phpunit`` or ``ddev composer test`` and it will execute the ``phpunit`` command.
This approach can be useful if you want to run other commands in addition to PHPUnit such as PHPStan, PHP Code Sniffer or Drupal Check. Each command can be added to the script and they will each be executed.
If needed, you can still pass additional arguments and options to the command by appending ``--`` followed by the arguments.
Locally, ensure that the command is prefixed with ``ddev`` so that it is run within the container. This ensures that the correct PHP version etc is used.
Step 2: Adding more test methods
--------------------------------
2a. Ensure that anonymous users cannot access admin pages
Now that we’re sure that the front page loads correctly, lets also check anonymous users cannot access the administration area. This test is very similar to the previous one, though instead we’re making a GET request to ``/admin`` and ensuring that the response code is 403 (forbidden).
As this functionality is provided by Drupal core by default, this should pass automatically.
..code:: php
/** @test */
public function the_admin_page_is_not_accessible_to_anonymous_users() {
Now let’s check that an administrator user *can* access the admin pages.
This introduces some new concepts. We need to create a user to begin with, and assign it some permissions. Because tests may be included within Drupal core a contributed module, permissions need to be added to users directly as modules won’t know about roles that are specific to your site.
The ``BrowserTestBase`` class gives access to a number of helper methods, including ones for creating and logging-in users (``createUser`` and ``drupalLogin`` respectively). When creating a user, the first argument is an array of permission names to add. In this case, we can make the user an admin user by adding the ``access administration pages`` permission.
..code:: php
/** @test */
public function the_admin_page_is_accessible_by_admin_users() {
Again, as this functionality is provided by Drupal core by default, this should pass. However, we can be confident that the test is doing what’s needed by making it fail by removing or changing the assigned permissions, or not logging in the user before accessing the page.
Step 3: Building a blog
-----------------------
3a. Anonymous users should be able to view the blog page
Let’s start by building a blog page. This will look very similar to the admin page tests, but instead we’ll be testing the ``/blog`` page.
..code:: php
<?php
// tests/src/Functional/BlogPageTest.php
namespace Drupal\my_module\Functional;
use Drupal\Tests\BrowserTestBase;
use Symfony\Component\HttpFoundation\Response;
class BlogPageTest extends BrowserTestBase {
protected $defaultTheme = 'stark';
protected static $modules = [
'my_module',
];
/** @test */
public function the_blog_page_loads_for_anonymous_users_and_contains_the_right_text() {
$this->drupalGet('blog');
$session = $this->assertSession();
$session->statusCodeEquals(Response::HTTP_OK);
}
}
This test will fail as there’s no route for ``/blog`` and no View that generates that page. Because of this, the response code will be a 404 instead of the 200 that we want.
Current response status code is 404, but 200 expected.
3b: Add a route for the blog page
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We’ll create a blog page using a custom route in the module. You could also do this with the Views module by creating a View with a page on that path, and exporting the configuration into the module’s ``config/install`` directory.
To add a route, we need to create a ``my_module.routing.yml`` file.
We set our path to ``/blog``, specify the Controller to use and which permission the needs to have to access the page.
If we run the tests now, we get an access denied error (403 response).
Current response status code is 403, but 200 expected.
3c: Fix permission error
~~~~~~~~~~~~~~~~~~~~~~~~
Because we need to node module to be able to access the ``access content`` permission, we need to enable it within our tests.
We can do this by adding it to the ``$modules`` array within the test.
..code:: diff
protected static $modules = [
+ 'node',
'my_module',
];
Now the error has changed, and is now returning a 500 response because we’ve specified a Controller that doesn’t exist.
Current response status code is 500, but 200 expected.
3d: Add the BlogPageController
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Let’s create the ``BlogPageController``.
::
mkdir src/Controller
Let’s start by creating a minimal controller, that returns an empty render array. Because we didn’t specify a method to use within the route file, we use PHP’s ``__invoke()`` method.
..code:: php
<?php
// src/Controller/BlogPageController
namespace Drupal\my_module\Controller;
class BlogPageController {
public function __invoke(): array {
return [];
}
}
This is enough for the test to pass. Though it just returns an empty page, it now returns the correct 200 response code.
OK (1 test, 3 assertions)
This is how the page looks in a browser:
..figure:: docs/images/1.png
:alt:
3e: Refactor, add more assertions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now that the test is passing, we can do some refactoring and make the test more robust by ensuring that the correct text is displayed.
..code:: diff
public function the_blog_page_loads_for_anonymous_users_and_contains_the_right_text() {
$this->drupalGet('/blog');
$session = $this->assertSession();
$session->statusCodeEquals(Response::HTTP_OK);
+ $session->responseContains('<h1>Blog</h1>');
+ $session->pageTextContains('Welcome to my blog!');
}
The page title is created by the ``_title`` value within the routing file, but no page text has been added yet so this will cause the test to fail.
Behat: The text "Welcome to my blog!" was not found anywhere in the
text of the current page.
To fix this, we can return some text from the BlogPageController rather than an empty render array.
..code:: diff
namespace Drupal\my_module\Controller;
+ use Drupal\Core\StringTranslation\StringTranslationTrait;
class BlogPageController {
+ use StringTranslationTrait;
public function __invoke(): array {
- return [];
+ return [
+ '#markup' => $this->t('Welcome to my blog!'),
+ ];
}
}
Now the tests will pass because we’re returning the correct text.
OK (1 test, 3 assertions)
..figure:: docs/images/2.png
:alt:
Step 4. Getting blog posts
--------------------------
4a Creating our first kernel test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We’ll be using an ArticleRepository class to get the blog posts from the database, and this is also a good time to switch to writing kernel tests as we don’t need to check any responses from the browser.
Within the tests directory, create a new ``Kernel`` directory.
::
mkdir tests/src/Kernel
And an ``ArticleRepositoryTest`` class.
..code:: php
<?php
// tests/src/Kernel/ArticleRepositoryTest.php
namespace Drupal\Tests\my_module\Kernel;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
class ArticleRepositoryTest extends EntityKernelTestBase {
/** @test */
public function it_returns_blog_posts() {
}
}
This test looks very similar to the functional ones that we’ve already written, except it extends a different base class.
This test is extending ``EntityKernelTestBase`` as we’re working with entities and this performs some useful setup steps for us. There are different base classes that can be used though based on what you need - including ``KernelTestBase`` and ``ConfigFormTestBase``.
4b. Starting with an assertion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Let’s write this test 'backwards' and start with the 'assert' phase.
We know that the end objective for this test is to have 3 article nodes returned, so let’s add that assertion first.
..code:: diff
/** @test */
public function it_returns_blog_posts() {
+ $this->assertCount(1, $articles);
}
As we aren’t yet returning any articles, or even creating that variable, the test is going to fail, but we can move on to getting articles.
Undefined variable: articles
4c. Trying to use the ArticleRepository
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As the test name suggests, we’re going to be retrieving the articles from an ``ArticleRepository`` service - though this doesn’t exist yet, but let’s let the tests tell us that.
Because this is a kernel test, we have access to the container, and we can use it to retrieve our repository service.
Running the test now gives us a different error, and tells us what the next step is:
Symfony: You have requested a non-existent service "Drupal\_module".
4d. Creating an article repository
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
..code:: bash
mkdir src/Repository
To begin with, let’s create a basic ``ArticleRepository`` class.
..code:: php
<?php
// my_module/src/Repository/ArticleRepository
namespace Drupal\my_module\Repository;
class ArticleRepository {
}
We also need to create a ``my_module.services.yml`` file that we can use to register the ``ArticleRepository`` as a service.
..code:: yaml
# my_module.services.yml
services:
Drupal\my_module\Repository\ArticleRepository: ~
Within ``ArticleRepositoryTest``, we need to add the import statement for the ``ArticleRepository`` as well enabling the module.
..code:: diff
+ use Drupal\my_module\Repository\ArticleRepository;
+ public static $modules = [
+ 'my_module',
+ ];
We’ve fixed the missing repository, though we still haven’t created the ``$articles`` variable or given it a value yet.
Undefined variable: articles
4e. Adding the ``getAll()`` method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We’ll use a ``getAll()`` method on the repository to retrieve the articles from the database, and use the value of this for the ``$articles`` variable:
This method doesn’t exist on the repository yet, so the test will fail.
Error : Call to undefined method Drupal\_module::getAll()
Let’s fix that by adding the ``getAll()`` method. For now, have it return an empty array.
..code:: php
// my_module/Repository/ArticleRepository.php
public function getAll(): array {
return [];
}
Now we’ve got everything in place, and the test failure is because we aren’t returning the correct number of articles.
Failed asserting that actual size 0 matches expected size 3.
We can fix this by building up the ``ArticleRepository`` class.
4f. Building up the ArticleRepository
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``ArticleRepository`` needs to return some articles. We can do this by injecting the ``EntityTypeManager`` and using it to return nodes from the ``getAll()`` method rather than the empty array.
..code:: diff
+ use Drupal\Core\Entity\EntityTypeManagerInterface;
Within our services file, we now need to add the ``EntityTypeManager`` as an argument so that it’s used to create the ``ArticleRepository``. Currently we don’t have enough arguments.
ArgumentCountError : Too few arguments to function
Drupal\_module::\_\_construct(), 0 passed and exactly 1 expected
The quickest way to do that is to enable autowiring for the ArticleRepository within ``my_module.services.yml``. This will automatically inject services rather than needing to specify each argument individually.
We now know that only article nodes are returned, but *all* articles are being returned. On our blog, we only want to published articles to be displayed.
Let’s create another test for this.
..code:: diff
+ /** @test */
+ public function only_published_articles_are_returned() {
We already know that only articles are returned, so in this test we can focus on the published status. We can create a number of articles, some which are published and some which are unpublished.
..code:: diff
/** @test */
public function only_published_articles_are_returned() {
Use ``createNode()`` again to create some article nodes, each with a different ``created`` date to match our assertion. This is to ensure that the test doesn’t pass by default.
..code:: diff
/** @test */
public function nodes_are_ordered_by_date_and_returned_newest_first() {
+ $this->createNode(['type' => 'article', 'created' => (new DrupalDateTime('-2 days'))->getTimestamp()]);
+ $this->createNode(['type' => 'article', 'created' => (new DrupalDateTime('-1 week'))->getTimestamp()]);
+ $this->createNode(['type' => 'article', 'created' => (new DrupalDateTime('-1 hour'))->getTimestamp()]);
+ $this->createNode(['type' => 'article', 'created' => (new DrupalDateTime('-1 year'))->getTimestamp()]);
+ $this->createNode(['type' => 'article', 'created' => (new DrupalDateTime('-1 month'))->getTimestamp()]);
In the browser, we should see our list of articles.
..figure:: docs/images/3.png
:alt:
Step 5: Creating a custom Post class
------------------------------------
What if we wanted to return a custom ``Post`` class from the repository with its own data and logic rather than a generic Drupal node? As the repository is responsible for finding and returning nodes, we can make changes there and return what we want.
Let's start by changing one of our existing tests.
5a: Changing the existing test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In ``ArticleRepositoryTest`` we have existing assertions as to what type of object is returned. Currently, this should be an instance of a ``Node::class``. Let's change that to a new ``Post::class`` and also change the ``label`` method to a more desciriptive ``getTitle()``.
This will return an array of ``Post`` objects, and change the failure message as we're calling a method that we've not yet added.
Error: Call to undefined method Drupal\_module::getTitle()
To do this, let's start by adding a Unit test.
Step 6: Unit testing the Post class
-----------------------------------
6a: Creating a PostTest class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a ``Unit`` directory, an ``Entity`` sub-directory, and a ``PostTest.php`` file. Typically, unit tests match the directory structure in ``src`` and the class name that they're testing.
::
mkdir -p tests/src/Unit/Entity
..code:: php
<?php
namespace Drupal\Tests\my_module\Unit\Entity;
use Drupal\Tests\UnitTestCase;
class PostTest extends UnitTestCase {
}
For the first test case, let's ensure that the title is returned.
As we are working with a unit test, we can't interact with the database in the same way that we can with functional or kernel tests. This means that using methods like ``Node::create`` won't work in unit tests, so we need to create our own mock node and tell it what to return.
..code:: php
$node = $this->createMock(NodeInterface::class);
$node->expects($this->once())
->method('label')
->willReturn('Test post');
This ensures that the ``label()`` method will only be called once and that it will return the string ``Test post``.
As this is the same value as our expection in the test, this test should now pass.
However, whilst the unit tests are all passing, one of the kernel tests is now failing.
6e. Fixing the ArticleRepository test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get ``ArticleRepositoryTest`` passing again, we need to update the ``getAll()`` method and add the node as an argument to the create ``Post``.
..code:: diff
return array_map(function (NodeInterface $node): Post {
- return new Post();
+ return new Post($node);
}, $articles);
6f: Only article nodes should be used for Posts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently any node is able to be passed to the ``Post`` class. Let's ensure that only article nodes can be added by adding a check and throwing an Exception.
..code:: php
/** @test */
public function it_throws_an_exception_if_the_node_is_not_an_article() {