如何在PHPUnit中測試由受測試的構造函數調用的方法?例如下面的簡單代碼將不起作用,因爲當我聲明存根方法時,存根對象已經被創建並且我的方法被調用,未被標記。保存由類的構造函數調用的方法
類測試:
class ClassA {
private $dog;
private $formatted;
public function __construct($param1) {
$this->dog = $param1;
$this->getResultFromRemoteServer();
}
// Would normally be private, made public for stubbing
public getResultFromRemoteServer() {
$this->formatted = file_get_contents('http://whatever.com/index.php?'.$this->dog);
}
public getFormatted() {
return ("The dog is a ".$this->formatted);
}
}
測試代碼:
class ClassATest extends PHPUnit_Framework_TestCase {
public function testPoodle() {
$stub = $this->getMockBuilder('ClassA')
->setMethods(array('getResultFromRemoteServer'))
->setConstructorArgs(array('dog52'))
->getMock();
$stub->expects($this->any())
->method('getResultFromRemoteServer')
->will($this->returnValue('Poodle'));
$expected = 'This dog is a Poodle';
$actual = $stub->getFormatted();
$this->assertEquals($expected, $actual);
}
}
我聽到你的聲音,我同意。上面的代碼我只是爲了便於說明而激動起來,但它反映了我正在處理的代碼。 <繼續下一條評論,我繼續按Enter> – jontyc 2011-04-05 07:26:11
我會看到如何彈出遠程調用後適合真正的代碼。這只是其中一個原本沒有課程的情況,因爲它不是必需的,但由於易於測試和嘲笑而增加了它。 – jontyc 2011-04-05 07:33:36
@stebbo如果您有任何其他問題,請隨時通過聊天進行下載。 – Gordon 2011-04-05 07:35:22