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

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

我知道我们可以测试使用该特性的类,但是我想知道是否有更好的方法。

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

编辑

一种选择是在测试类本身中使用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');
    }
}

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章