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;
            }
        }
4

2 回答 2

2

正是出于这个原因,我没有在单元测试中测试异常消息的确切内容——它们往往是可变的。

相反,您有两个选择:

  1. 明确派生一个新Exception的基于类以抛出此方法(例如“RelatedFilesExistedException”类)。单元测试可以简单地检查是否返回了正确的异常类型,而不必担心与消息文本完全匹配。

  2. 仅部分匹配异常消息(您必须为此编写自己的测试代码,而不是回复ExpectedException属性)。

于 2010-08-12T11:20:14.183 回答
0
  1. 为 Herbie 博士建议的不同事物创建不同的异常类。
  2. 我不会对正常的控制流使用异常。还有其他语言结构,例如 if-else。例外是针对异常行为。
  3. 我不会让用户点击他们不允许点击的按钮。显示消息而不是按钮可以更加用户友好。
于 2010-08-12T11:37:31.770 回答