调试单元测试由于StackOverflow异常而失败

时间:2013-03-11 11:30:22

标签: c# .net unit-testing stack-overflow

每当单元测试由于StackOverflowException单元测试过程立即退出而失败时 - 找出发生的事情(我所知道的)的唯一方法是调试获得的单元测试过程的崩溃转储按照此处的步骤

获取StackOverflowException被抛出时运行的单元测试名称的最简单方法是什么?即使在调试单元测试时,我也很难在堆栈底部找到当前单元测试的名称,Visual Studio也不会在调试窗口中显示整个堆栈,因为它太大了。

有没有办法在没有收集和调试故障转储的情况下找出哪个单元测试失败了?

2 个答案:

答案 0 :(得分:1)

this other question中所述,除非自己抛出,否则无法捕获堆栈溢出异常。

因此,作为解决问题的方法(不是真正的解决方案),您可以在代码中插入一个方法调用来检测堆栈溢出,然后手动抛出异常并稍后捕获它。

[TestClass]
public class TestStackOverflowDetection
{
    [TestMethod]
    public void TestDetectStackOverflow()
    {
        try
        {
            InfiniteRecursion();
        }
        catch (StackOverflowException e)
        {
            Debug.WriteLine(e);
        }
    }

    private static int InfiniteRecursion(int i = 0)
    {
        // Insert the following call in all methods that
        // we suspect could be part of an infinite recursion 
        CheckForStackOverflow(); 

        // Force an infinite recursion
        var j = InfiniteRecursion(i) + 1;
        return j;
    }

    private static void CheckForStackOverflow()
    {
        var stack = new System.Diagnostics.StackTrace(true);
        if (stack.FrameCount > 1000) // Set stack limit to 1,000 calls
        {
            // Output last 10 frames in the stack
            foreach (var f in stack.GetFrames().Reverse().Take(30).Reverse())
                Debug.Write("\tat " + f);

            // Throw a stack overflow exception
            throw new StackOverflowException();
        }
    }

答案 1 :(得分:1)

查看RuntimeHelpers.EnsureSufficientExecutionStack方法(http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.ensuresufficientexecutionstack.aspx)。您可能希望在递归方法中调用它以提前获得InsufficientExecutionStackException