我需要编写一个测试来验证我的代码是否可以处理在不安全的上下文中发生的 AccessViolationException(或任何其他 WIN32 损坏状态异常 - CSE),通常是通过调用第 3 方库。 这一切都应该在 .net 4.0 上使用 C# 完成。
我找到了这个相关问题 How to handle AccessViolationException和这篇相关文章 http://dotnetslackers.com/articles/net/All-about-Corrupted-State-Exceptions-in-NET4.aspx ,其中解释了如何捕捉这些 CSE 及其背景。
所以我想在测试中激发 WIN32 CSE,以确保在我的应用程序中正确处理。像这样的东西:
一些要测试的示例类:
public class MyExceptionHandler
{
[HandleProcessCorruptedStateExceptions]
public void HandleCorruptedStateException()
{
try
{
//Force genuine unsafe AccessViolationException
//not just a throw new AccessViolationException
}
catch(Exception e)
{
//Log/cleanup/other
}
}
public void DoesNotHandleCorruptedStateException()
{
try
{
//Force genuine unsafe AccessViolationException
//not just a throw new AccessViolationException
}
catch (Exception e)
{
//Log/cleanup/other
}
}
}
一个测试:
class MyTest
{
[Test]
public void ShouldVerifyThatAnAccessViolationExceptionIsHandledCorrectly()
{
var handler = new MyExceptionHandler();
Assert.DoesNotThrow(() => handler.HandleCorruptedStateException());
}
[Test]
public void ShouldVerifyThatAnAccessViolationExceptionIsNotHandledCorrectly()
{
var handler = new MyExceptionHandler();
Assert.Throws<AccessViolationException>(() => handler.DoesNotHandleCorruptedStateException());
}
}
有没有人建议如何在不做太多工作的情况下实现这一目标(例如,编写一个导致此异常的不安全库)。
亲切的问候
更新:为了匹配我的最终解决方案,感谢 JaredPar。
public class MyExceptionHandler
{
[HandleProcessCorruptedStateExceptions]
public void HandleCorruptedStateException()
{
try
{
var ptr = new IntPtr(42);
Marshal.StructureToPtr(42, ptr, true);
}
catch(Exception e)
{
//Log/cleanup/other
}
}
public void DoesNotHandleCorruptedStateException()
{
try
{
var ptr = new IntPtr(42);
Marshal.StructureToPtr(42, ptr, true);
}
catch (Exception e)
{
//Log/cleanup/other
}
}
}
提示: 要从命令行手动验证这一点,请使用一个简单的控制台应用程序:
class Program
{
static void Main(string[] args)
{
var handler = new MyExceptionHandler();
if (args.Length > 1)
{
handler.HandleCorruptedStateException();
}
else
{
handler.DoesNotHandleCorruptedStateException();
}
}
}
最佳答案
尝试以下操作
var ptr = new IntPtr(42);
Marshal.StructureToPtr(42, ptr, true);
这不能保证根据 CLI 规范抛出 AccessViolationException
,但它会在我知道的每个平台上抛出
关于c# - 如何测试 AccessViolationException 的处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839615/