[英]Need advice for testing in php
我對測試很新。 我有一個webapp,可以存儲有關書籍的書籍和信息。
如果我調用我的路線/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
}
如何在不向goodreads發出http請求的情況下測試它? 我需要驗證語言是否在數據庫中。 我可以使用fetchLanguages()
來獲取fetchLanguages()
。 但是我怎么能這個函數存根/模擬(我不知道正確的術語)?
我使用Laravel和PHPUnit。
你需要的就是這個 - 存在BookService類。 但是,由於您直接實例化它,因此將其存根並不容易。 您應該將它注入Book類,這樣您就可以在測試中注入一個存根(通過構造函數注入或通過提供一個setter來覆蓋$ this-> bookService)。
典型設置如下所示:
$serviceMock = $this->getMock('BookService');
$serviceMock->method('fetchLanguages')->willReturn(<some hard-coded-result-here>);
$book = new Book($serviceMock);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.