简体   繁体   English

C#如何快速生成正确的错误以进行测试

[英]C# how to generate a proper error quickly for testing purposes

I have some code in my error handler I need to test against a realistic error. 我的错误处理程序中有一些代码我需要针对实际错误进行测试。 How can I generate an error that has a full stack trace and is just as realistic as a runtime error. 如何生成具有完整堆栈跟踪的错误,并且与运行时错误一样真实。

I am using a general catch on an exception. 我正在使用异常的常规捕获。 So do not need a specific type of exception in this particular case. 因此,在这种特殊情况下不需要特定类型的异常。

Thanks 谢谢

object m = null;
string s = m.ToString();

Instant NullReferenceException . Instant NullReferenceException

关于什么

throw new Exception("this is a test");

You can throw any kind of .Net exception by calling 您可以通过调用抛出任何类型的.Net异常

throw new OutOfMemoryException();
throw new IndexOutOfRangeException();
throw new ArgumentNullException();

The exception names can be any dotnet exceptions. 例外名称可以是任何dotnet例外。 you can even create and throw your own specific exceptions. 您甚至可以创建并抛出自己的特定异常。

To get a list of the CLR exceptions, in VS click on the debug menu and then the exceptions menu. 要获取CLR例外列表,请在VS中单击调试菜单,然后单击例外菜单。

One DivideByZeroException coming up!: 一个DivideByZeroException即将出现!:

int i = 0;
int j = 1 / i;

您可以生成空引用异常...或除零异常。

我建议你尝试使用模拟框架,例如Moq和Rhino Mocks,然后传入你希望捕获的相关Exception。

throw new IndexOutOfRangeException();

how about the good old division by zero? 如此优秀的老师除零?

5 / 0 5/0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中使用反射设置私有惰性<T>以进行测试? - How to set a private lazy<T> with reflection for testing purposes in C#? C#将CPU保持在指定使用率附近/用于测试目的 - C# Keep CPU at/near designated percent usage for testing purposes 如何在 C# 中快速转换 lambda 中的对象 - How to quickly cast an object in lambda in C# 如何快速阅读c#中的Excel电子表格 - How to read an Excel spreadsheet in c# quickly 是什么使得设计师不是每个事件都可用,如何在VB.NET中快速生成C#中的处理程序? - What makes it so that not every event is available in the designer, and how can I quickly generate handlers in C# like in VB.NET? 用于学习目的的复杂 C# - Complicated C# for learning purposes 如何使用C#为UIAutomation调整UIA窗口的大小? - How to resize UIA window for UIAutomation purposes, using C#? 如何为测试目的模拟网络故障(在C#中)? - How to simulate network failure for test purposes (in C#)? C#:测试实体框架 FromSql 以确保语法正确 - C#: Testing Entity Framework FromSql to ensure proper syntax 在C#代码函数错误超时中,但是在SQL Server中,它执行迅速 - In C# code function error timeout but in SQL Server it executes quickly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM