在上一篇我們把程式改為『依賴注入』的方式,最終的測試案例的程式碼為
<?php
// tests/PttCrawlerTest
namespace Recca0120\Ithome30\Tests;
use PHPUnit\Framework\TestCase;
use Recca0120\Ithome30\PttCrawler;
use Recca0120\Ithome30\HttpClient;
class PttCrawlerTest extends TestCase
{
public function test_fetch_board_page()
{
$crawler = new PttCrawler(new FakeHttpClient());
$records = $crawler->all();
self::assertEquals([
'name' => 'Gossiping',
"nuser" => '12185',
'class' => '綜合',
'title' => '[八卦]不停重複今日公祭明日忘記',
], $records[0]);
}
}
class FakeHttpClient extends HttpClient
{
public function get()
{
return file_get_contents(__DIR__ . '/fixtures/ptt_home.html');
}
}
雖然這樣的測試 code 已經算滿好理解了,但還是必須得再多出一個 FakeHttpClient 來輔助測試,總覺得不太舒服,這時我們就可以導入 Mockery 來讓我們的測試程式更為簡潔
composer require --dev mockery/mockery
<?php
// tests/PttCrawlerTest
namespace Recca0120\Ithome30\Tests;
use Mockery;
use PHPUnit\Framework\TestCase;
use Recca0120\Ithome30\HttpClient;
use Recca0120\Ithome30\PttCrawler;
class PttCrawlerTest extends TestCase
{
public function test_fetch_board_page()
{
/**
* 使用 Mockery::mock 直接建立一個假物件
* @var Mockery\Mock|HttpClient $httpClient
*/
$httpClient = Mockery::mock(HttpClient::class);
// 模擬 allows 來指定 HttpClient::get 並用 andReturn 回傳 html
$httpClient
->allows('get')
->andReturn(file_get_contents(__DIR__ . '/fixtures/ptt_home.html'));
$crawler = new PttCrawler($httpClient);
$records = $crawler->all();
self::assertEquals([
'name' => 'Gossiping',
"nuser" => '12185',
'class' => '綜合',
'title' => '[八卦]不停重複今日公祭明日忘記',
], $records[0]);
}
}
再導入 Mockery 之後測試是不是就變的更容易閱讀了