DEV Community

suin
suin

Posted on

20

How to test traits by unit testing

As PHP traits can not be instance by its self, it seems impossible to unit test. However, by making ordinary classes that use a trait, you can write test code for traits.

<?php

trait Greetable {
    public function hello(int $repeat): string {
        return str_repeat('Hello!', $repeat);
    }
}

class GreetableBeings {
    use Greetable;
}

class GreetableTest {
    public function testHello() {
        $g = new GreetableBeings();
        assert($g->hello(1) === 'Hello!');
        assert($g->hello(2) === 'Hello!Hello!');
        assert($g->hello(3) === 'Hello!Hello!Hello!');
    }
}

(new GreetableTest)->testHello();
Enter fullscreen mode Exit fullscreen mode

Since anonymous class can be used from PHP 7, we no longer have to bother to create a class for testing.

<?php

trait Greetable {
    public function hello(int $repeat): string {
        return str_repeat('Hello!', $repeat);
    }
}

class GreetableTest {
    public function testHello() {
        $g = new class { use Greetable; }; // anonymous class
        assert($g->hello(1) === 'Hello!');
        assert($g->hello(2) === 'Hello!Hello!');
        assert($g->hello(3) === 'Hello!Hello!Hello!');
    }
}

(new GreetableTest)->testHello();
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
reoring profile image
reoring

Nice article.

Collapse
 
hukuzatsu profile image
ピーターパン@エンジニア

I know about anonymous class in PHP7 at the first time.
Thank you for your valuable information:)

Collapse
 
carlpham profile image
CarlPham

Nice article

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay