【问题标题】:How to unit test PHP traits如何对 PHP 特征进行单元测试
【发布时间】:2015-09-13 23:58:07
【问题描述】:

我想知道是否有关于如何对 PHP 特征进行单元测试的解决方案。

我知道我们可以测试一个使用 trait 的类,但我想知道是否有更好的方法。

提前感谢您的任何建议:)

编辑

另一种方法是在测试类本身中使用 Trait,我将在下面演示。

但是我并不热衷于这种方法,因为无法保证特征、类和PHPUnit_Framework_TestCase(在此示例中)之间没有类似的方法名称:

这是一个示例特征:

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;
    }
}

及其测试:

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');
    }
}

【问题讨论】:

  • 请提供您尝试执行此操作但不起作用的代码。这会帮助别人帮助你。
  • @AdamB,我自己写了first answer,里面有示例代码。但请注意,它不像某些东西坏了或不起作用,我只是想知道是否有任何好的方法可以直接而不是通过单元测试使用该特征的类来间接地对特征进行单元测试。坦克

标签: php unit-testing phpunit traits


【解决方案1】:

您可以使用类似于测试抽象类的具体方法来测试特征。

PHPUnit has a method getMockForTrait 将返回一个使用该特征的对象。然后您可以测试特征函数。

这是文档中的示例:

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

【讨论】:

    【解决方案2】:

    您也可以使用 getObjectForTrait ,然后根据需要断言实际结果。

    class YourTraitTest extends TestCase
    {
        public function testGetQueueConfigFactoryWillCreateConfig()
        {
            $obj = $this->getObjectForTrait(YourTrait::class);
    
            $config = $obj->getQueueConfigFactory();
    
            $this->assertInstanceOf(QueueConfigFactory::class, $config);
        }
    
        public function testGetQueueServiceWithoutInstanceWillCreateConfig()
        {
            $obj = $this->getObjectForTrait(YourTrait::class);
    
            $service = $obj->getQueueService();
    
            $this->assertInstanceOf(QueueService::class, $service);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 2012-01-08
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2013-05-22
      • 1970-01-01
      • 2013-09-30
      相关资源
      最近更新 更多