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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay