Drupal offers a few different types of tests you can use, but how do you know which one to pick?
This is how I decide based on what I need to test by asking these questions:
Do I need to test HTTP requests and responses?
Do I need to make GET or POST requests to a URL and check its response code, e.g. to check the endpoint exists, that I get an expected "Page not found" or "Forbidden" message, or to check if an item was created or updated?
If so, use a Functional test like BrowserTestBase.
Do I need to test with JavaScript?
BrowserTestBase doesn't include JavaScript, so use a FunctionaJavaScript test if needed.
Do I need to retrieve services from the service/Dependency Injection container?
If I don't need to make HTTP requests but need access to the service container, I use a Kernel test such as KernelTestBase.
There's more setup for kernel tests compared to functional tests, such as installing the required configuration and creating schema tables in the database. However, having less installed means the tests run faster.
There are different base classes, such as EntityKernelTestBase, that can be used depending on the situation to simplify the setup.
Can I test the code in isolation without the service container?
If I can test the code without needing the service container and mock simple dependencies, then use a Unit test.
These are very fast to run, but you can overuse mocks and sometimes test the mocks instead of the code you intended to test.
Here's the thing
As well as the regular unit test type, Drupal offers various types of test that can be used depending on the situation.
I like to start with functional tests first and switch to kernel or unit tests when needed. They're slower to run but easier to write as they need less setup and arguably provide the most value.
If you're just getting started with testing, they're probably the quickest to learn too.
- Oliver
Was this interesting?
About me
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.