2010-08-12 146 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. 我不会让用户点击他们不允许点击的按钮。显示消息而不是按钮可以更方便用户使用。