Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何显示异常消息的简单问题_C#_Unit Testing_Nhibernate_Nunit 2.5 - Fatal编程技术网

C# 如何显示异常消息的简单问题

C# 如何显示异常消息的简单问题,c#,unit-testing,nhibernate,nunit-2.5,C#,Unit Testing,Nhibernate,Nunit 2.5,我有一个看似愚蠢而简单的问题,但我几乎不知道如何继续下去 我的问题是: 如何修改异常消息并对其进行自定义,以使单元测试仍然通过 实际上,我想将异常消息自定义为“Student”Johny“had related files!”,修改API异常消息后,单元测试失败 约翰尼是一个可能会改变的变量 任何帮助如何我可以实现上述。谢谢 在我的测试课上,我有 [ExpectedException(ExceptionType = typeof(Exception), ExpectedMess

我有一个看似愚蠢而简单的问题,但我几乎不知道如何继续下去

我的问题是:

如何修改异常消息并对其进行自定义,以使单元测试仍然通过

实际上,我想将异常消息自定义为“Student”Johny“had related files!”,修改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;
            }
        }

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

相反,您有两个选择:

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

  • 仅部分匹配异常消息(您必须为其编写自己的测试代码,而不是在
    ExpectedException
    属性上进行回复)

  • 为不同的事物创建不同的异常类,如Herbie博士所建议的
  • 我不会对正常的控制流使用异常。还有其他的语言结构,比如if-else。异常是指异常行为
  • 我不允许用户点击他们不允许点击的按钮。显示消息而不是按钮可以更方便用户

  • 谢谢你的回复。我可以举一个例子来说明如何做到这一点吗?在VisualStudio中,创建一个新的类文件并删除类定义。然后使用“Exception”代码段创建一个新的异常类(键入“Exception”,然后使用TAB启动该代码段),将该类重命名为“RelatedFileExistException”。在代码中,抛出新的RelatedFileExistException,而不是抛出新的异常。在单元测试中使用[ExpectedException(ExceptionType=typeof(RelatedFilesExistException)]