您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit对抽象类进行模仿-getMockForAbstractClass的使用
发布时间:2021-09-24 22:06:30编辑:雪饮阅读()
上篇了解了phpunit对trait的使用类进行模仿,这里将了解下对抽象类的模仿,该模仿与对trait的应用者类的模仿类同,只是使用了getMockForAbstractClass() 方法返回一个抽象类的仿件对象。
实例:
AbstractClassTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
abstract class AbstractClass
{
public function concreteMethod()
{
return $this->abstractMethod();
}
public abstract function abstractMethod();
}
final class AbstractClassTest extends TestCase
{
public function testConcreteMethod(): void
{
$stub = $this->getMockForAbstractClass(AbstractClass::class);
$stub->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($stub->concreteMethod());
}
}
use PHPUnit\Framework\TestCase;
abstract class AbstractClass
{
public function concreteMethod()
{
return $this->abstractMethod();
}
public abstract function abstractMethod();
}
final class AbstractClassTest extends TestCase
{
public function testConcreteMethod(): void
{
$stub = $this->getMockForAbstractClass(AbstractClass::class);
$stub->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($stub->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\AbstractClassTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.005, Memory: 20.00 MB
OK (1 test, 1 assertion)
关键字词:phpunit,getMockForAbstractClass