8 lines
1.7 KiB
Markdown
8 lines
1.7 KiB
Markdown
|
---
|
||
|
date: 2025-05-13
|
||
|
title: Writing your own test traits
|
||
|
permalink: /daily/2025/05/13/writing-your-own-test-traits
|
||
|
---
|
||
|
|
||
|
<p>In Drupal, there are different types of automated tests we can write.</p><p>The most common I use are Functional, Kernel and Unit - which I explain about in <a href="/presentations/tdd-test-driven-drupal">my Test Driven Drupal talk</a>.</p><p>If I'm writing multiple of the same type, I'll often create my own base test class that extends <code>BrowserTestCase</code>, <code>KernelTestCase</code> or whatever base class I need rather than extending it directly.</p><p>This allows me to write custom helper functions and share behaviour between the tests.</p><p>An example is the <code>createDailyEmailNode</code> method I wrote to simplify creating daily emails in my tests <a href="/daily/2025/05/11/email-archive-tome">since migrating to Tome</a>.</p><p>But, what if you want to do this for different types of test?</p><p>Enter, traits.</p><p>Traits are a way of reusing code without inheritance - meaning without extending a base class.</p><p>I can use a trait in my functional and kernel tests whilst both extend their required base classes.</p><p>I did this with my <code>createDailyEmailNode</code> method so I could re-use it in both types of tests when counting the number of sent daily emails.</p><p>To see this, you can <a href="https://code.oliverdavies.uk/opdavies/oliverdavies.uk/src/commit/88ec3d9e5136c6cbefebba063863ef1a058f4b09/modules/opd_daily_emails/tests/src">look at the code</a> on my Forgejo instance.</p><p>P.S. If you want to learn how to write automated tests in Drupal, subscribe to <a href="http://localhost:8888/atdc">my free 10-day email course</a>.</p>
|