PHPUnit模拟包装器实例

时间:2016-08-18 08:40:43

标签: phpunit integration-testing

我有这个包装器:

class APIWrapper {
    protected static $clientClass = \Hardcoded_API; // from a library
    protected $client;

    public function __construct() {
        $this->client = new self::$clientClass(array_merge(self::$config, $config));
    }

    /**
     * Does something.
     *
     * @throws SomeException
     */
    public function act() {
         $this->client->doSomething();
    }

    public static function setClientClass($clientClass) {
         self::$clientClass = $clientClass;
    }
}

现在让我说我正在测试使用这个包装器的函数:

class UnrelatedFunction {
    public function callAPI() {
        $wrapper = new APIWrapper();
        try {
            $wrapper->act();
        } catch (SomeException $e) {
            // ... do other things
        }
    }
}

class UnrelatedFunctionsTest extends PHPUnit_Framework_TestCase {
    public function testUnrelatedFunctionException() {
        $unrelatedFunction = new UnrelatedFunction();
        $this->setExpectedException('SomeException');
        // this call triggers the APIWrapper
        $unrelatedFunction->callAPI();

        // Some assertions here...
    }
}

我需要能够验证UnrelatedFunction::callAPI()是否已从异常中恢复工作。在这种情况下,如何模拟\Hardcoded_API类,在调用SomeException时抛出act(),并将其传递到APIWrapper::setClientClass(),以便我可以测试行为?

0 个答案:

没有答案