2010-08-12 64 views
1

我有一個問題,可能看起來很愚蠢和簡單,但我幾乎不知道如何繼續下去。簡單的問題如何顯示異常消息

我的問題是:

如何修改異常消息並進行自定義,這樣我仍然有我的單元測試及格?

其實我想自定義異常消息給「學生」Johny「有相關文件!」並修改API異常消息,單元測試失敗。

佐尼是可以改變一個變量...

任何幫助,我怎麼能實現以上。由於


在我的測試類我有

 [ExpectedException(ExceptionType = typeof(Exception), ExpectedMessage = "The DELETE statement conflicted with the REFERENCE constraint \"FK_Issue_Priority\"")] 

其實我使用NHibernate和我的API,我處理異常如下:

catch (NHibernate.ADOException exception) 
     { 
      if (exception.InnerException.GetType().Equals(typeof(System.Data.SqlClient.SqlException))) 
      { 
       if (exception.InnerException.Message.Contains("FK_Issue_Priority")) 
       { 
        throw new Exception("The DELETE statement conflicted with the REFERENCE constraint \"FK_Issue_Priority\""); 
       } 
       else 
       { 
        throw new Exception("A database error occurred while trying to add the customer to project relation please the see inner exception for details", exception.InnerException); 
       } 
      } 
      else 
      { 
       throw exception; 
      } 
     } 

回答

2

我不考我的單元中的異常消息的確切內容正是出於這個原因 - 它們往往是可變的。

相反,你有兩個選擇:

  1. 派生一個新Exception基於類的明確對該方法拋出(例如「RelatedFilesExistedException」級)。單元測試可以簡單地檢查返回正確的異常類型,而不必擔心完全匹配消息文本。

  2. 只能部分匹配異常消息(爲此您必須編寫自己的測試代碼,並且不要在ExpectedException屬性上回復)。

+0

感謝您的回覆。我能舉一個例子說明如何做到這一點? – learning 2010-08-12 11:48:37

+1

在Visual Studio中,創建一個新的類文件並刪除類定義。然後使用'Exception'片段創建一個新的異常類(鍵入'Exception',然後TAB來觸發片段),將該類重命名爲'RelatedFilesExistException'。在你的代碼中,拋出新的RelatedFilesExistException而不是拋出新的Exception。 在你單元測試中使用[ExpectedException(ExceptionType = typeof(RelatedFilesExistException)] – 2010-08-12 12:01:26

0
  1. 創建像赫比醫生不同的事情表明不同的異常類。
  2. 我不會在正常控制流程中使用異常。還有其他的語言結構,比如if-else。例外情況是出乎意料的行爲。
  3. 我不會讓用戶點擊他們不允許點擊的按鈕。顯示消息而不是按鈕可以更方便用戶使用。