PHPUnit9.0 測試替身-對 Web 服務(wù)(Web Services)進(jìn)行上樁或模仿

2022-03-22 14:45 更新

當(dāng)應(yīng)用程序需要和 web 服務(wù)進(jìn)行交互時,會想要在不與 web 服務(wù)進(jìn)行實際交互的情況下對其進(jìn)行測試。為了給 web 服務(wù)創(chuàng)建樁件或仿件,可以像使用 ?getMock()?那樣使用 ?getMockFromWsdl()?。唯一的區(qū)別是 ?getMockFromWsdl()? 所返回的樁件或者仿件是基于以 WSDL 描述的 web 服務(wù),而 ?getMock()? 返回的樁件或者仿件是基于 PHP 類或接口的。

示例 8.20 展示了如何用 ?getMockFromWsdl()? 來對(例如)?GoogleSearch.wsdl? 中描述的 web 服務(wù)上樁。

示例 8.20 給 web 服務(wù)上樁

<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class GoogleTest extends TestCase
{
    public function testSearch(): void
    {
        $googleSearch = $this->getMockFromWsdl(
          'GoogleSearch.wsdl', 'GoogleSearch'
        );

        $directoryCategory = new stdClass;
        $directoryCategory->fullViewableName = '';
        $directoryCategory->specialEncoding = '';

        $element = new stdClass;
        $element->summary = '';
        $element->URL = 'https://phpunit.de/';
        $element->snippet = '...';
        $element->title = '<b>PHPUnit</b>';
        $element->cachedSize = '11k';
        $element->relatedInformationPresent = true;
        $element->hostName = 'phpunit.de';
        $element->directoryCategory = $directoryCategory;
        $element->directoryTitle = '';

        $result = new stdClass;
        $result->documentFiltering = false;
        $result->searchComments = '';
        $result->estimatedTotalResultsCount = 3.9000;
        $result->estimateIsExact = false;
        $result->resultElements = [$element];
        $result->searchQuery = 'PHPUnit';
        $result->startIndex = 1;
        $result->endIndex = 1;
        $result->searchTips = '';
        $result->directoryCategories = [];
        $result->searchTime = 0.248822;

        $googleSearch->expects($this->any())
                     ->method('doGoogleSearch')
                     ->will($this->returnValue($result));

        /**
         * $googleSearch->doGoogleSearch() 現(xiàn)在會返回樁結(jié)果,
         * 并不會調(diào)用 web 服務(wù)的 doGoogleSearch() 方法。
         */
        $this->assertEquals(
          $result,
          $googleSearch->doGoogleSearch(
            '00000000000000000000000000000000',
            'PHPUnit',
            0,
            1,
            false,
            '',
            false,
            '',
            '',
            ''
          )
        );
    }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號