doudong4532 2015-06-26 22:43
浏览 30
已采纳

如何对PHP特征进行单元测试

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 approaches.

Thanks for any advice in advance :)

EDIT

One alternative is to use the Trait in the test class itself as I'm going to demonstrate bellow.

But I'm not that keen on this approach since there is no guaranty there are no similar method names between the trait, the class and also the PHPUnit_Framework_TestCase (in this example):

Here is an example trait:

trait IndexableTrait
{
    /** @var int */
    private $index;

    /**
     * @param $index
     * @return $this
     * @throw \InvalidArgumentException
     */
    public function setIndex($index)
    {
        if (false === filter_var($index, FILTER_VALIDATE_INT)) {
            throw new \InvalidArgumentException('$index must be integer.');
        }

        $this->index = $index;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getIndex()
    {
        return $this->index;
    }
}

and its test:

class TheAboveTraitTest extends \PHPUnit_Framework_TestCase
{
    use TheAboveTrait;

    public function test_indexSetterAndGetter()
    {
        $this->setIndex(123);
        $this->assertEquals(123, $this->getIndex());
    }

    public function test_indexIntValidation()
    {
        $this->setExpectedException(\Exception::class, '$index must be integer.');
        $this->setIndex('bad index');
    }
}
  • 写回答

1条回答 默认 最新

  • doulang7699 2015-06-29 20:20
    关注

    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:

    <?php
    trait AbstractTrait
    {
        public function concreteMethod()
        {
            return $this->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());
        }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号