我有这个包装器:
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()
,以便我可以测试行为?