2017-01-25 41 views
0

我打算對函數A做一個調用另一個函數B的函數A,我該如何替換函數B的返回來繼續成功地繼續我的測試我該如何取代函數返回

public function A($parameter = null){ 
// do something 
$response_B = $this->B(); 
// continue with the function A 
} 

注意:函數B在SQL中對數據庫進行查詢。在我的測試中,我不想做任何查詢,只是我想預先定義函數B的一個結果。 我嘗試過使用Mocks和Stubs,但實際上我完全不瞭解它。 請對不起我的英語

+1

你所說的'替換功能B'的回報意思? 嘗試添加示例代碼以幫助我們更好地理解 – Antony

+0

您可以上傳您的代碼嗎? – Svekke

+0

你可以使用燈具或模擬,但不知道,你真正想要做什麼,它很難幫助你 – Oliver

回答

0

的功能實例:

function pass(){ 
$test = check(3); 
return $test; //returns true when 3 is parameter used to call function check() 
} 

function check($int) { 
if ($int == 3) { 
return true; 
} else { 
return false; 
} 
0

所以你想要的東西,所謂的「嘲諷」,這不會與一個簡單的函數工作。

,使之簡單。(代碼未測試)

class MySpecialClass 
{ 
public function doSomeSpecialThings(){ 
    $response = $this->doFancySQL(); 
    return $response; 
} 
} 

所以如果你要處理的方法調用,你必須把它解壓到一個外部類,並注入其

class MySpecialClass 
{ 
    public function setFancySqlInterface(FancySqlInterface $fancySqlInterface){ 
$this->fancySqlInterface = $fancySqlInterface; 
} 
public function doSomeSpecialThings(){ 
    $response = $this->fancySqlInterface->doFancySQL(); 
    return $response; 
} 
} 

與此,現在您可以在您的測試中使用方法setFancySqlInterface與假類返回一個特定的響應。

您可以創建一個假的類或使用「模擬框架」這一任務

爲例,你可以在這裏看到

https://github.com/BlackScorp/guestbook/blob/master/tests/UseCase/ListEntriesTest.php#L35我創建假實體,並將它們添加到假庫https://github.com/BlackScorp/guestbook/blob/master/tests/UseCase/ListEntriesTest.php#L70

希望你明白我的意思是:d