PHPUnit9.0 測試替身-對特質(zhì)(Trait)與抽象類進行模仿

2022-03-22 14:43 更新

?getMockForTrait()? 方法返回一個使用了特定特質(zhì)(trait)的仿件對象。給定特質(zhì)的所有抽象方法將都被模仿。這樣就能對特質(zhì)的具體方法進行測試。

示例 8.18 測試特質(zhì)的具體方法

<?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
    {
        $mock = $this->getMockForTrait(AbstractTrait::class);

        $mock->expects($this->any())
             ->method('abstractMethod')
             ->will($this->returnValue(true));

        $this->assertTrue($mock->concreteMethod());
    }
}

?getMockForAbstractClass()? 方法返回一個抽象類的仿件對象。給定抽象類的所有抽象方法將都被模仿。這樣就能對抽象類的具體方法進行測試。

示例 8.19 測試抽象類的具體方法

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號