loading...

How to test traits by unit testing

suin profile image suin ・1 min read

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();

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();

Posted on Sep 2 '19 by:

suin profile

suin

@suin

qiita.com over 20,000 Contribution/Japanese translation reviewer of "Implementing Domain-Driven Design"/ Founder of Craftsman Software, Inc. /Developer of shouldbee.at/PHP/DDD/Scala/Docker/OOP/Go

Discussion

markdown guide
 
 

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