Set up test traits dynamically

4 years ago
php
// Setup:

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function setUp(): void
    {
        // Set up traits dynamically.
        // Uses the naming convention: "setUpNameOfMyTrait".
        $this->afterApplicationCreated(function () {
            foreach (class_uses_recursive($this) as $trait) {
                if (method_exists($this, $method = 'setUp' . class_basename($trait))) {
                    call_user_func([$this, $method]);
                }
            }
        });

        parent::setUp();
    }
}

// Usage:

trait Authenticated
{
    protected $user;

    // This will be automatically set up on test classes that uses this trait.
    public function setUpAuthenticated()
    {
        $this->user = User::factory()->create();
        $this->actingAs($this->user);
    }
}

When cleaning your tests using traits, you often end up having to override the setUp method for each test class that uses the trait in order to initialise some sort of logic. This code enables us to dynamically set up traits when they are used in test classes by using the naming convention: setUpMyTraitName.

Note that Laravel already support a similar behaviour for Eloquent trait via the bootMyTraitName convention.

Discussions

Would you like to chime in?

You must be a member to start a new discussion.

Fortunately, it only takes two click to become one. See you on the other side! 🌸

Become a Member