如何在PHPUnit中存根一个由test的构造函数中的类调用的方法?例如,下面的简单代码将无法工作,因为在我声明存根方法时,已经创建了存根对象,并且我的方法被调用,取消存储.
要测试的类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud) 我有一堂课如下
class AccountsProcessor{
protected $remoteAccountData = [];
/**
* Process the data passed as an input array
*/
public function process($inputCsv): array
{
$this->loadRemoteData($inputCsv);
return $this->remoteAccountData;
}
/**
* Given a data retrieved from Local CSV file, iterate each account, retrieve status info from server
* and save result to instance variable array remoteAccountData
*
* @param $inputCsv
*/
protected function loadRemoteData($inputCsv)
{
foreach ($inputCsv as $account)
{
// Lookup status data on remote server for this account and add …Run Code Online (Sandbox Code Playgroud)