PHPUnit测试,模拟对外部API的调用

PHPUnit测试,模拟对外部API的调用,php,api,unit-testing,phpunit,Php,Api,Unit Testing,Phpunit,我有如下的课程 class AccountsProcessor{ protected $remoteAccountData = []; /** * Process the data passed as an input array */ public function process($inputCsv): array { $this->loadRemoteData($inputCsv); return

我有如下的课程

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 it to RemoteAccountData Array
            $this->remoteAccountData["{$account[0]}"] 
                 = $this->CallApi("GET", "http://examplurl.com/v1/accounts/{$account[0]}");
        }
    }

    /**
     * Curl call to Remote server to retrieve missing status data on each account
     *
     * @param $method
     * @param $url
     * @param bool $data
     * @return mixed
     */
    private function CallAPI($method, $url, $data = false)
    {

       ..... internal code ...
    }
}
该类有一个公共进程方法,该方法接受数组并将其传递给受保护的函数,该函数迭代数组中的每个帐户,并使用CURL调用外部API

我的问题是,当我对这个类进行单元测试时,我只想测试process方法,因为这是唯一的公共方法,其他方法是私有的或受保护的

我可以很容易地这样做:

protected $processor;

protected function setUp()
{
    $this->processor = new AccountsProcessor();
}
/** @test */
public function it_works_with_correctly_formatted_data()
{

    $inputCsv = [
        ["12345", "Beedge", "Kevin", "5/24/16"],
        ["8172", "Joe", "Bloggs", "1/1/12"]
    ];

    $processedData = $this->processor->process($inputCsv);
    $this->assertEquals("good", $processedData[0][3]);
}
但是运行这个测试实际上调用了外部API


如何模拟来自私有函数CallAPI()的调用?

这里测试的内容不太清楚,但是假设
CallAPI
中有一些逻辑,您有两个选项-解耦传输并存根它,或者存根API。任何一种方法都需要一些重构以使其可测试。您可以查看并创建一个服务类,将其注入到您的类中,以便单元测试可以注入一个模拟类而不是实际的类