相关疑难解决方法(0)

对类的构造函数调用的方法进行存根

如何在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)

php phpunit

22
推荐指数
2
解决办法
1万
查看次数

PHPUnit测试,模拟调用外部API

我有一堂课如下

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)

php api phpunit unit-testing

5
推荐指数
0
解决办法
1527
查看次数

标签 统计

php ×2

phpunit ×2

api ×1

unit-testing ×1