In Drupal, there are different types of automated tests we can write.
The most common I use are Functional, Kernel and Unit - which I explain about in my Test Driven Drupal talk.
If I'm writing multiple of the same type, I'll often create my own base test class that extends BrowserTestCase
, KernelTestCase
or whatever base class I need rather than extending it directly.
This allows me to write custom helper functions and share behaviour between the tests.
An example is the createDailyEmailNode
method I wrote to simplify creating daily emails in my tests since migrating to Tome.
But, what if you want to do this for different types of test?
Enter, traits.
Traits are a way of reusing code without inheritance - meaning without extending a base class.
I can use a trait in my functional and kernel tests whilst both extend their required base classes.
I did this with my createDailyEmailNode
method so I could re-use it in both types of tests when counting the number of sent daily emails.
To see this, you can look at the code on my Forgejo instance.
P.S. If you want to learn how to write automated tests in Drupal, subscribe to my free 10-day email course.