2016-12-27 67 views
1

我對測試非常陌生。我有一個web應用程序,用於存儲關於書籍的書籍和信息。需要在php中測試的建議

如果我打電話給我的路線/store/它會觸發我的store方法並在我的數據庫中創建一本新書。這是簡化的方法:

Book.php類文件:

public function __construct() { 
    $this->bookService = new BookService(); 
} 

public function store() { 
    $input = /* get post input values */ 
    $this->createDatabaseEntry($input); 
} 

private function createDatabaseEntry($input) { 
    // Creating database entry 
    $book = /* bla bla */ 

    $languages = $this->bookService->fetchLanguages($book->goodreads_id); 
    // And here i loop over the $languages and store them all in a extra table. 
} 

,在這裏我有一個其他服務類BookService.php

public function fetchLanguages($goodreads_id) { 
    // Here i make an guzzle http call to a other service from goodreads.com 
} 

如何測試這個而不做HTTP請求goodreads ?我需要驗證語言在數據庫中。我可以使用燈具fetchLanguages()。但是,我怎樣才能存根/模擬(我不知道正確的術語)這個函數?

我使用Laravel和PHPUnit。

回答

0

你需要的就是這個 - 存根BookService類。因爲你直接實例化它,所以存根並不是那麼容易。您應該將其注入到Book類中,以便您可以在測試中注入存根(可以通過構造函數注入或通過提供setter來覆蓋$ this-> bookService)。

一個典型的設置是這樣的:

$serviceMock = $this->getMock('BookService'); 
$serviceMock->method('fetchLanguages')->willReturn(<some hard-coded-result-here>); 
$book = new Book($serviceMock);