Jus*_*tin 14 .net c# stack-overflow unit-testing
每当单元测试由于StackOverflowException单元测试过程立即退出而失败时- 找出发生的事情(我所知道的)的唯一方法是调试通过遵循这里找到的步骤获得的单元测试过程的故障转储
获取在StackOverflowException抛出时运行的单元测试名称的最简单方法是什么?即使在调试单元测试时,我也很难找到当前单元测试的名称,因为它在堆栈的底部并且Visual Studio不会在调试窗口中显示整个堆栈,因为它太大了.
有没有办法找出哪个单元测试失败而没有收集和调试崩溃转储?
正如另一个问题中提到的,除非您自己抛出堆栈溢出异常,否则您无法真正捕获它。
因此,作为问题的解决方法(不是真正的解决方案),您可以在代码中插入方法调用来检测堆栈溢出,然后手动抛出异常并稍后捕获它。
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1497 次 |
| 最近记录: |