如何对PHP特性进行单元测试 [英] How to unit test PHP traits

查看:72
本文介绍了如何对PHP特性进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以对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 :)

编辑

一种选择是在我要演示的时候,在测试类中使用Trait.

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

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

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):

以下是一个示例特征:

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

推荐答案

您可以使用与测试Abstract Class的具体方法类似的方法来测试Trait.

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

PHPUnit具有getMockForTrait 方法,该方法将返回使用特征的对象.然后,您可以测试特征功能.

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

以下是文档中的示例:

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

这篇关于如何对PHP特性进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆