C# 如何显示异常消息的简单问题
我有一个看似愚蠢而简单的问题,但我几乎不知道如何继续下去 我的问题是: 如何修改异常消息并对其进行自定义,以使单元测试仍然通过 实际上,我想将异常消息自定义为“Student”Johny“had related files!”,修改API异常消息后,单元测试失败 约翰尼是一个可能会改变的变量 任何帮助如何我可以实现上述。谢谢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
在我的测试课上,我有
[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
属性上进行回复)谢谢你的回复。我可以举一个例子来说明如何做到这一点吗?在VisualStudio中,创建一个新的类文件并删除类定义。然后使用“Exception”代码段创建一个新的异常类(键入“Exception”,然后使用TAB启动该代码段),将该类重命名为“RelatedFileExistException”。在代码中,抛出新的RelatedFileExistException,而不是抛出新的异常。在单元测试中使用[ExpectedException(ExceptionType=typeof(RelatedFilesExistException)]