2014-02-06 33 views
4

我正在嘗試使用Behat和我的第一個功能,我面臨的問題我不知道如何實現預期的例外。如何實現預期的異常?

我發現問題https://github.com/Behat/Behat/issues/140和robocoder正在討論Behat使用的一種可能的方法。但似乎他們並沒有真正處理例外情況。

我的觀點是實現強制的異常處理。我不希望任何構造捕獲所有異常並忘記它們。

一種可能的方式是:

When <player> transfers <transfer> from his account it should fail with <error> 

實施

try { 
    ... 
} catch (\Exception $ex) { 
    assertEquals($error, $ex->getMessage()); 
} 

我不喜歡的場景描述。我想使用,然後使用關鍵字,例如。

When <player> transfers <transfer> from his account 
Then it should fail with error <error> 

這說明有缺點,我需要兩個方法:

method1($arg1, $arg2) { 
    // Test the transfer 
} 

method2($arg1, $arg2) { 
    // Check if the exception is the right one 
} 

爲了能夠方法2異常需要存儲檢查。
我看到的唯一可能的方法是使用try/catch並將其存儲到變量中。
別人會抓到它,什麼都不做。運行測試時,沒有人會注意到。

如何防止異常被丟棄?
是否有其他人實現了類似的場景?

感謝您的任何提示。

編輯

貝哈特方面:從實體類

playerTransfer($player, $amount) {  
    $player->transfer($amount); 
} 

方法:

transfer($amount) { 
    if ($this->getWealth() < $amount) { 
     throw NotEnoughMoney(); 
    } 

    ... 
} 

回答

0

我認爲這個問題是在您的實現。您是否在「從他的賬戶轉賬時」檢查轉賬是否成功?你需要檢查它嗎?

故障測試:

When <player> transfers <transfer> from his account 
Then I should see error <error> 

成功的一步:

When <player> transfers <transfer> from his account 
Then I should see "transfer successful" 
+0

你如何處理從他的帳戶由* 轉讓拋出的異常* ?請參閱我的問題的第二部分。 – CSchulz

+0

它不應該拋出異常,應拋出異常「然後我應該......」。你可以發佈一些僞實施? –

+0

添加了一些實現。回覆晚了非常抱歉。 – CSchulz

2

總是試圖捕捉方法成果上下文類領域,例如:在預期異常,當

//inside Behat context class method 
try { 
    $this->outcome = $func(); 
} 
catch(\Exception $ex) { 
    $this->outcome = $ex; 
} 

現在下一步只需檢查$ this->結果是否爲帶有消息/代碼的instanceof期望異常。

0

下面是我成功做到了在我的項目,我不得不重複,直到舉行成立的情況下幾步:

/** 
* @Given /^I execute some conditions$/ 
*/ 
public function executeConditions() 
{ 
    $flag = 1; 
    do { 
     try { 
      <steps to be executed till the condition holds true> 
      $flag=1; 
     } catch (\Exception $ex) { 
      $flag = 0; 
     } 
    }while ($flag>0); 
}