如何测试AccessViolationException的处理

Chr*_*sen 17 .net c# unsafe access-violation c#-4.0

我需要编写一个测试来验证我的代码可以处理AccessViolationException(或任何其他WIN32损坏状态异常 - CSE),它通常通过调用第三方库来处理不安全的上下文.这应该都是使用C#on .net 4.0完成的.

我发现了这个相关的问题如何处理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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一个测试:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有人建议如何在没有太多工作的情况下实现这一目标(例如,写一个导致此异常的不安全的lib).

亲切的问候

更新: 为了匹配我的最终解决方案,感谢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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

提示: 要从命令行手动使用简单的控制台应用程序验证此操作:

class Program
{
    static void Main(string[] args)
    {
        var handler = new MyExceptionHandler();

        if (args.Length > 1)
        {
            handler.HandleCorruptedStateException();
        }
        else
        {
            handler.DoesNotHandleCorruptedStateException();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 28

请尝试以下方法

var ptr = new IntPtr(42);
Marshal.StructureToPtr(42, ptr, true);
Run Code Online (Sandbox Code Playgroud)

这不能保证AccessViolationException按照CLI规范抛出,但它会在我所知道的每个平台上抛出