panthro's avatar

Writing a test for a trait?

I have a trait that uploads images, saves to a table and makes the relationship to model the trait is added to, for example:

$user->addImage($file)

How can I test this?

Do I write a test for the trait itself?

Do I write a test for each model that the trait is added to, e.g. user, product, etc.?

Do I write a test as a trait that is included in each model, so I can check that a) the trait works and b) the trait is correctly attached to the model in question?

0 likes
2 replies
automica's avatar
automica
Best Answer
Level 54

@panthro whilst you can't write a test for a trait directly, you can create a simple class in your test and then include the trait within that:

namespace App\Mixin;
 
trait MyTrait {
    public function returnState(bool $state): bool {
        return $state;
    }
}

use App\Mixin\MyTrait;
use PHPUnit\Framework\TestCase;
 
class MyTraitTest extends TestCase {
    public function testReturnStateAnonymous(): void {
        $trait = new class {
            use MyTrait;
        };
 
        self::assertTrue($trait->returnState(true));
        self::assertFalse($trait->returnState(false));
    }
}

If you are relying on your trait within a class, I would be happy to see the tests for the trait included in that class's tests.

That way you can ensure that your class still uses the trait. Testing trait on its own would allow someone to remove the trait from a specific class and not necessarily know that you did.

see https://doeken.org/blog/testing-traits-in-phpunit

2 likes

Please or to participate in this conversation.