How to unit test PHP traits

后端 未结 2 1583
别跟我提以往
别跟我提以往 2021-01-30 20:36

I want to know if there is a solution on how to unit-test a PHP trait.

I know we can test a class which is using the trait, but I was wondering if there are better appro

2条回答
  •  孤城傲影
    2021-01-30 21:01

    You can test a Trait using a similar to testing an Abstract Class' concrete methods.

    PHPUnit has a method getMockForTrait which will return an object that uses the trait. Then you can test the traits functions.

    Here is the example from the documentation:

    abstractMethod();
        }
    
        public abstract function abstractMethod();
    }
    
    class TraitClassTest extends PHPUnit_Framework_TestCase
    {
        public function testConcreteMethod()
        {
            $mock = $this->getMockForTrait('AbstractTrait');
    
            $mock->expects($this->any())
                 ->method('abstractMethod')
                 ->will($this->returnValue(TRUE));
    
            $this->assertTrue($mock->concreteMethod());
        }
    }
    ?>
    

提交回复
热议问题