您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit对对特质(Trait)进行模仿
发布时间:2021-09-24 21:30:13编辑:雪饮阅读()
getMockForTrait() 方法返回一个使用了特定特质(trait)的仿件对象。给定特质的所有抽象方法将都被模仿。
下面实例将模仿一个使用了trait的对象并调用trait的”实现”了的抽象方法。
并匹配该抽象方法被执行任意次数以及断言其执行的返回值为true。
TraitClassTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
trait AbstractTrait
{
public function concreteMethod()
{
return $this->abstractMethod();
}
public abstract function abstractMethod();
}
final class TraitClassTest extends TestCase
{
public function testConcreteMethod(): void
{
//`getMockForTrait()` 方法返回一个使用了特定特质(trait)的仿件对象
$mock = $this->getMockForTrait(AbstractTrait::class);
//预期abstractMethod抽象方法会被调用0次或更多次(即任意次数)这是any的匹配作用
//模仿trait的抽象abstractMethod返回值为true
$mock->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($mock->concreteMethod());
}
}
use PHPUnit\Framework\TestCase;
trait AbstractTrait
{
public function concreteMethod()
{
return $this->abstractMethod();
}
public abstract function abstractMethod();
}
final class TraitClassTest extends TestCase
{
public function testConcreteMethod(): void
{
//`getMockForTrait()` 方法返回一个使用了特定特质(trait)的仿件对象
$mock = $this->getMockForTrait(AbstractTrait::class);
//预期abstractMethod抽象方法会被调用0次或更多次(即任意次数)这是any的匹配作用
//模仿trait的抽象abstractMethod返回值为true
$mock->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($mock->concreteMethod());
}
}
运行结果:
C:\Users\Administrator\PhpstormProjects\untitled\organizing>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\organizing\tests\TraitClassTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.013, Memory: 20.00 MB
OK (1 test, 1 assertion)
关键字词:phpunit,Trait