Ali*_*Ali 36 php phpunit unit-testing traits
我想知道是否有关于如何对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;
}
}
Run Code Online (Sandbox Code Playgroud)
及其测试:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
Sch*_*eis 69
您可以使用类似于测试Abstract Class的具体方法来测试Trait.
PHPUnit有一个方法getMockForTrait,它将返回一个使用该特征的对象.然后你可以测试traits函数.
以下是文档中的示例:
<?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());
}
}
?>
Run Code Online (Sandbox Code Playgroud)
Ste*_*eve 15
从 PHP 7 开始,我们现在可以使用匿名类......
$class = new class {
use TheTraitToTest;
};
// We now have everything available to test using $class
Run Code Online (Sandbox Code Playgroud)
如果需要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);
}
}
Run Code Online (Sandbox Code Playgroud)